From 26a06d5058566971c67ab76c8467d6ee9034ac06 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Wed, 24 Aug 2022 11:58:38 +0800 Subject: [PATCH 01/73] [fix] anisotropy rotation seam line, optimize macros in standard.effect (#12529) --- .../effect-macros/common-macros.chunk | 3 + .../surfaces/module-functions/common-vs.chunk | 2 +- .../assets/effects/surfaces/standard.effect | 68 +++++++++++-------- 3 files changed, 43 insertions(+), 30 deletions(-) diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk index e75589ce87..1ca12e5104 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk @@ -36,6 +36,9 @@ #endif // varying-undependent macros +#ifndef CC_SURFACES_FLIP_UV + #define CC_SURFACES_FLIP_UV 0 +#endif #ifndef CC_SURFACES_USE_TWO_SIDED #define CC_SURFACES_USE_TWO_SIDED 0 #endif diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk index ae45d43473..c1f3c01509 100644 --- a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk @@ -95,7 +95,7 @@ void CCSurfacesVertexWorldTransform(inout SurfacesStandardVertexIntermediate In) void CCSurfacesVertexTransformUV(inout SurfacesStandardVertexIntermediate In) { - #if SAMPLE_FROM_RT + #if CC_SURFACES_FLIP_UV CC_HANDLE_RT_SAMPLE_FLIP(In.texCoord); #if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP CC_HANDLE_RT_SAMPLE_FLIP(In.texCoord1); diff --git a/editor/assets/effects/surfaces/standard.effect b/editor/assets/effects/surfaces/standard.effect index 2d983927dc..cb06da9d49 100644 --- a/editor/assets/effects/surfaces/standard.effect +++ b/editor/assets/effects/surfaces/standard.effect @@ -7,26 +7,27 @@ CCEffect %{ - vert: standard-vs frag: standard-fs properties: &props - tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } - albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } - occlusion: { value: 1.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - roughness: { value: 0.8, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - metallic: { value: 0.6, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } - emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } - emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleParam.xyz } - normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } - anisotropyShape: { value: 1.0, target: anisotropyParam.x, editor: { parent: IS_ANISOTROPY, slide : true, range : [0.0, 1.0] , step : 0.0001 } } - anisotropyRotation: { value: 0.0, target: anisotropyParam.y, editor: { parent: IS_ANISOTROPY, slide : true, range : [0, 1.0] , step : 0.0001 } } - mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } - normalMap: { value: normal } - pbrMap: { value: grey } - metallicRoughnessMap: { value: grey } - occlusionMap: { value: white } - emissiveMap: { value: grey } - anisotropyMap: { value: black, editor : { parent: IS_ANISOTROPY } } + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 1.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + roughness: { value: 0.8, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.6, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } + emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleParam.xyz } + normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + anisotropyIntensity: { value: 1.0, target: anisotropyParam.x, editor: { parent: IS_ANISOTROPY, slide : true, range : [0.0, 1.0] , step : 0.0001 } } + anisotropyRotation: { value: 0.0, target: anisotropyParam.y, editor: { parent: IS_ANISOTROPY, slide : true, range : [0, 1.0] , step : 0.0001 } } + anisotropyMapResolutionHeight: { value: 0.0, target: anisotropyParam.w, editor: { parent: FIX_ANISOTROPIC_ROTATION_MAP } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + normalMap: { value: normal } + pbrMap: { value: grey } + occlusionMap: { value: white } + emissiveMap: { value: grey } + anisotropyMap: { value: black, editor : { parent: IS_ANISOTROPY } } + anisotropyMapNearestFilter: { value: black, editor : { parent: FIX_ANISOTROPIC_ROTATION_MAP } } - &forward-add vert: standard-vs frag: standard-fs @@ -84,7 +85,7 @@ CCProgram shared-ubos %{ vec4 pbrParams; vec4 emissive; vec4 emissiveScaleParam; - vec2 anisotropyParam; + vec4 anisotropyParam; }; }% @@ -154,9 +155,6 @@ CCProgram surface-fragment %{ #if USE_PBR_MAP uniform sampler2D pbrMap; #endif - #if USE_METALLIC_ROUGHNESS_MAP - uniform sampler2D metallicRoughnessMap; - #endif #if USE_OCCLUSION_MAP uniform sampler2D occlusionMap; #endif @@ -166,6 +164,7 @@ CCProgram surface-fragment %{ #endif #if IS_ANISOTROPY && USE_ANISOTROPY_MAP uniform sampler2D anisotropyMap; + uniform sampler2D anisotropyMapNearestFilter; #endif #pragma define OCCLUSION_CHANNEL r @@ -243,6 +242,22 @@ CCProgram surface-fragment %{ anisotropyShape *= tex.x; #endif + // fix rotation map seam line of black and white + #if FIX_ANISOTROPIC_ROTATION_MAP + #if IS_ANISOTROPY && USE_ANISOTROPY_MAP + vec4 reference = texture(anisotropyMapNearestFilter, DEFAULT_UV); + vec2 oneTap = vec2(0.0, 1.0 / anisotropyParam.w); + float threshold = 0.2; + // scan more taps for stable result + vec4 sample1 = texture(anisotropyMapNearestFilter, DEFAULT_UV + oneTap); + vec4 sample2 = texture(anisotropyMapNearestFilter, DEFAULT_UV - oneTap); + if (abs(sample1.y - reference.y) > threshold || abs(sample2.y - reference.y) > threshold) { + tex.y = reference.y; + } + anisotropyRotation = fract(anisotropyParam.y * PI * 0.5 + tex.y) * PI2; + #endif + #endif + isRotation = 1.0; return vec4(anisotropyShape, anisotropyRotation, 0.0, 0.0); } @@ -268,11 +283,6 @@ CCProgram surface-fragment %{ pbr.z *= res.METALLIC_CHANNEL; pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; #endif - #if USE_METALLIC_ROUGHNESS_MAP - vec4 metallicRoughness = texture(metallicRoughnessMap, DEFAULT_UV); - pbr.z *= metallicRoughness.METALLIC_CHANNEL; - pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL; - #endif #if USE_OCCLUSION_MAP pbr.x *= texture(occlusionMap, DEFAULT_UV).OCCLUSION_CHANNEL; #endif From e59e33ef430d4264b0581125b1f197b7d495c5a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A2=81=E7=82=9C=E6=B5=B7?= <35713518+dogodo-cc@users.noreply.github.com> Date: Wed, 24 Aug 2022 14:49:16 +0800 Subject: [PATCH 02/73] [Feature] feat: add tracker (#12466) * feat: add tracker * feat: delete debug code * feat: dispatch track event * feat: delete async * feat: optimize code --- editor/inspector/assets/fbx/fbx.js | 1 + editor/inspector/assets/fbx/index.js | 25 +++++++++ editor/inspector/assets/fbx/material.js | 1 + editor/inspector/assets/fbx/model.js | 8 +-- .../inspector/components/particle-system.js | 51 +++++++++++++++++++ 5 files changed, 82 insertions(+), 4 deletions(-) diff --git a/editor/inspector/assets/fbx/fbx.js b/editor/inspector/assets/fbx/fbx.js index dacbb0a613..ed26af1b91 100644 --- a/editor/inspector/assets/fbx/fbx.js +++ b/editor/inspector/assets/fbx/fbx.js @@ -242,6 +242,7 @@ exports.methods = { }); this.dispatch('change'); + this.dispatch('track', { tab: 'fbx', prop, value: event.target.value }); }, /** * Update whether a data is editable in multi-select state diff --git a/editor/inspector/assets/fbx/index.js b/editor/inspector/assets/fbx/index.js index 029e6544c6..b69a6e6f13 100644 --- a/editor/inspector/assets/fbx/index.js +++ b/editor/inspector/assets/fbx/index.js @@ -149,3 +149,28 @@ exports.methods = { } }, }; + + +exports.listeners = { + 'track'(event) { + + if (event.args?.length) { + const { prop, value } = event.args[0]; + if (!value) { return; } // 只有被勾选的时候上报埋点 + + const trackMap = { + meshOptimizer: 'A100000', + 'fbx.smartMaterialEnabled': 'A100001', + disableMeshSplit: 'A100002', + }; + const trackId = trackMap[prop]; + if (trackId) { + Editor.Metrics._trackEventWithTimer({ + category: 'importSystem', + id: trackId, + value: 1, + }); + } + } + }, +}; diff --git a/editor/inspector/assets/fbx/material.js b/editor/inspector/assets/fbx/material.js index c10e4e0cf8..a342204bac 100644 --- a/editor/inspector/assets/fbx/material.js +++ b/editor/inspector/assets/fbx/material.js @@ -355,6 +355,7 @@ exports.methods = { }); this.dispatch('change'); + this.dispatch('track', { tab: 'material', prop, value: event.target.value }); }, /** * Update whether a data is editable in multi-select state diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index 44def8d59d..d9ed449ddd 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -363,7 +363,7 @@ const Elements = { }, }; -exports.update = function (assetList, metaList) { +exports.update = function(assetList, metaList) { this.assetList = assetList; this.metaList = metaList; this.asset = assetList[0]; @@ -377,7 +377,7 @@ exports.update = function (assetList, metaList) { } }; -exports.ready = function () { +exports.ready = function() { for (const prop in Elements) { const element = Elements[prop]; if (element.ready) { @@ -386,7 +386,7 @@ exports.ready = function () { } }; -exports.close = function () { +exports.close = function() { for (const prop in Elements) { const element = Elements[prop]; if (element.close) { @@ -410,8 +410,8 @@ exports.methods = { meta.userData[prop] = value; }); - this.dispatch('change'); + this.dispatch('track', { tab: 'model', prop, value: event.target.value }); }, setMeshOptimizerOptions(prop, event) { this.metaList.forEach((meta) => { diff --git a/editor/inspector/components/particle-system.js b/editor/inspector/components/particle-system.js index 4aed84e75a..b7149bd768 100644 --- a/editor/inspector/components/particle-system.js +++ b/editor/inspector/components/particle-system.js @@ -699,3 +699,54 @@ exports.style = /* css */` margin-left: 10px; } `; + +exports.listeners = { + async 'change-dump'(event) { + + const target = event.target; + if (!target) { + return; + } + + const dump = event.target.dump; + if (!dump) { + return; + } + + // renderMode选择mesh次数 + if (dump.path.endsWith('renderer.renderMode') && dump.value === 4) { + Editor.Metrics._trackEventWithTimer({ + category: 'particleSystem', + id: 'A100011', + value: 1, + }); + } + + // 粒子系统其他模块埋点 + const trackMap = { + 'noiseModule.enable': 'A100000', + 'shapeModule.enable': 'A100001', + velocityOvertimeModule: 'A100002', + forceOvertimeModule: 'A100003', + 'sizeOvertimeModule.enable': 'A100004', + 'rotationOvertimeModule.enable': 'A100005', + colorOverLifetimeModule: 'A100006', + textureAnimationModule: 'A100007', + 'limitVelocityOvertimeModule.enable':'A100008', + 'trailModule.enable': 'A100009', + 'renderer.useGPU': 'A1000010', + }; + + const dumpKey = Object.keys(trackMap).find(key => dump.path.endsWith(key)); + if (!dumpKey) { return; } + + const value = dump.type === 'Boolean' ? dump.value : dump.value.enable.value; + if (!value) { return; } + + Editor.Metrics._trackEventWithTimer({ + category: 'particleSystem', + id: trackMap[dumpKey], + value: 1, + }); + }, +}; From f18975a7a924d5efc868591977951b353280a4c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 24 Aug 2022 16:06:49 +0800 Subject: [PATCH 03/73] V3.6.1 se::Object private object add interfaces (#12515) --- .../cocos/bindings/jswrapper/PrivateObject.h | 75 ++-- native/cocos/bindings/jswrapper/v8/Object.h | 343 +++++++++++------- .../cocos/bindings/manual/jsb_conversions.h | 49 +-- native/cocos/bindings/manual/jsb_global.h | 34 +- 4 files changed, 277 insertions(+), 224 deletions(-) diff --git a/native/cocos/bindings/jswrapper/PrivateObject.h b/native/cocos/bindings/jswrapper/PrivateObject.h index ef2d7d73bd..85499c5b07 100644 --- a/native/cocos/bindings/jswrapper/PrivateObject.h +++ b/native/cocos/bindings/jswrapper/PrivateObject.h @@ -62,7 +62,7 @@ public: virtual void tryAllowDestroyInGC() const {} virtual bool isSharedPtr() const { return false; } - virtual bool isCCShared() const { return false; } + virtual bool isCCIntrusivePtr() const { return false; } friend se::Object; friend se::State; @@ -83,15 +83,18 @@ public: }; template -class SharedPrivateObject final : public TypedPrivateObject { +class SharedPtrPrivateObject final : public TypedPrivateObject { public: - SharedPrivateObject() = default; - explicit SharedPrivateObject(const std::shared_ptr &ptr) : _data(ptr) {} - explicit SharedPrivateObject(std::shared_ptr &&ptr) : _data(std::move(ptr)) {} - inline std::shared_ptr getData() const { + SharedPtrPrivateObject() = default; + explicit SharedPtrPrivateObject(const std::shared_ptr &ptr) : _data(ptr) {} + explicit SharedPtrPrivateObject(std::shared_ptr &&ptr) : _data(std::move(ptr)) {} + inline const std::shared_ptr& getData() const { return _data; } + inline std::shared_ptr& getData() { + return _data; + } constexpr bool isSharedPtr() const override { return true; } void *getRaw() const override { return _data.get(); } @@ -101,17 +104,20 @@ private: }; template -class CCSharedPtrPrivateObject final : public TypedPrivateObject { +class CCIntrusivePtrPrivateObject final : public TypedPrivateObject { public: - CCSharedPtrPrivateObject() = default; - explicit CCSharedPtrPrivateObject(const cc::IntrusivePtr &p) : _ptr(p) {} - explicit CCSharedPtrPrivateObject(cc::IntrusivePtr &&p) : _ptr(std::move(p)) {} - ~CCSharedPtrPrivateObject() override = default; + CCIntrusivePtrPrivateObject() = default; + explicit CCIntrusivePtrPrivateObject(const cc::IntrusivePtr &p) : _ptr(p) {} + explicit CCIntrusivePtrPrivateObject(cc::IntrusivePtr &&p) : _ptr(std::move(p)) {} + ~CCIntrusivePtrPrivateObject() override = default; + + inline const cc::IntrusivePtr& getData() const { return _ptr; } + inline cc::IntrusivePtr& getData() { return _ptr; } inline void *getRaw() const override { return _ptr.get(); } - inline bool isCCShared() const override { return true; } + inline bool isCCIntrusivePtr() const override { return true; } private: cc::IntrusivePtr _ptr; @@ -140,7 +146,7 @@ public: _ptr = nullptr; } - //bool *getValidAddr() { return &_validate; } + // bool *getValidAddr() { return &_validate; } void allowDestroyInGC() const override { _allowGC = true; @@ -150,28 +156,28 @@ public: } void *getRaw() const override { - //CC_ASSERT(_validate); + // CC_ASSERT(_validate); return _ptr; } private: T *_ptr = nullptr; - //bool _validate = true; + // bool _validate = true; mutable bool _allowGC = false; }; template inline std::shared_ptr TypedPrivateObject::share() { if (isSharedPtr()) { - return reinterpret_cast *>(this)->getData(); + return reinterpret_cast *>(this)->getData(); } CC_ASSERT(false); return std::shared_ptr(nullptr); } template inline cc::IntrusivePtr &TypedPrivateObject::ccShared() { - CC_ASSERT(isCCShared()); - return reinterpret_cast *>(this)->_ptr; + CC_ASSERT(isCCIntrusivePtr()); + return reinterpret_cast *>(this)->_ptr; } #if CC_DEBUG @@ -185,17 +191,6 @@ inline void inHeap(void *ptr) { } #endif -template -typename std::enable_if::value, PrivateObjectBase *>::type -cc_tmp_new_ptr(T *cobj) { - return ccnew CCSharedPtrPrivateObject(cc::IntrusivePtr(cobj)); -} -template -typename std::enable_if::value, PrivateObjectBase *>::type -cc_tmp_new_ptr(T *cobj) { - return ccnew SharedPrivateObject(std::shared_ptr(cobj)); -} - template inline PrivateObjectBase *make_shared_private_object(T *cobj) { // NOLINT static_assert(!std::is_same::value, "void * is not allowed"); @@ -203,18 +198,22 @@ inline PrivateObjectBase *make_shared_private_object(T *cobj) { // NOLINT #if CC_DEBUG inHeap(cobj); #endif - return cc_tmp_new_ptr(cobj); + if constexpr (std::is_base_of::value) { + return ccnew CCIntrusivePtrPrivateObject(cc::IntrusivePtr(cobj)); + } else { + return ccnew SharedPtrPrivateObject(std::shared_ptr(cobj)); + } } template -inline PrivateObjectBase *shared_private_object(std::shared_ptr &&ptr) { // NOLINT +inline PrivateObjectBase *shared_ptr_private_object(std::shared_ptr &&ptr) { // NOLINT static_assert(!std::is_base_of::value, "cc::RefCounted is not acceptable for shared_ptr"); - return ccnew SharedPrivateObject(std::forward>(ptr)); + return ccnew SharedPtrPrivateObject(std::forward>(ptr)); } template -inline PrivateObjectBase *shared_private_object(const std::shared_ptr &ptr) { // NOLINT +inline PrivateObjectBase *shared_ptr_private_object(const std::shared_ptr &ptr) { // NOLINT static_assert(!std::is_base_of::value, "cc::RefCounted is not acceptable for shared_ptr"); - return ccnew SharedPrivateObject(ptr); + return ccnew SharedPtrPrivateObject(ptr); } template @@ -228,13 +227,13 @@ inline PrivateObjectBase *rawref_private_object(T *ptr) { // NOLINT } template -inline PrivateObjectBase *ccshared_private_object(const cc::IntrusivePtr &ptr) { // NOLINT +inline PrivateObjectBase *ccintrusive_ptr_private_object(const cc::IntrusivePtr &ptr) { // NOLINT static_assert(std::is_base_of::value, "cc::RefCounted expected!"); - return ccnew CCSharedPtrPrivateObject(ptr); + return ccnew CCIntrusivePtrPrivateObject(ptr); } template -inline PrivateObjectBase *ccshared_private_object(T *cobj) { // NOLINT +inline PrivateObjectBase *ccintrusive_ptr_private_object(T *cobj) { // NOLINT static_assert(std::is_base_of::value, "cc::RefCounted expected!"); - return ccnew CCSharedPtrPrivateObject(cc::IntrusivePtr(cobj)); + return ccnew CCIntrusivePtrPrivateObject(cc::IntrusivePtr(cobj)); } } // namespace se diff --git a/native/cocos/bindings/jswrapper/v8/Object.h b/native/cocos/bindings/jswrapper/v8/Object.h index 2b7074117e..128fa58318 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.h +++ b/native/cocos/bindings/jswrapper/v8/Object.h @@ -27,6 +27,7 @@ #pragma once #include "../config.h" +#include "bindings/jswrapper/PrivateObject.h" #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 @@ -51,33 +52,33 @@ class Class; class ScriptEngine; /** - * se::Object represents JavaScript Object. - */ + * se::Object represents JavaScript Object. + */ class Object final : public RefCounter { public: /** - * @brief Creates a JavaScript Object like `{} or new Object()`. - * @return A JavaScript Object, or nullptr if there is an error. - * @note The return value (non-null) has to be released manually. - */ + * @brief Creates a JavaScript Object like `{} or new Object()`. + * @return A JavaScript Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object *createPlainObject(); /** - * @brief Creates a JavaScript Array Object like `[] or new Array()`. - * @param[in] length The initical length of array. - * @return A JavaScript Array Object, or nullptr if there is an error. - * @note The return value (non-null) has to be released manually. - */ + * @brief Creates a JavaScript Array Object like `[] or new Array()`. + * @param[in] length The initical length of array. + * @return A JavaScript Array Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object *createArrayObject(size_t length); /** - * @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer. - * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. - * @param[in] byteLength The number of bytes pointed to by the parameter bytes. - * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. - * @note The return value (non-null) has to be released manually. - * @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead. - */ + * @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + * @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead. + */ SE_DEPRECATED_ATTRIBUTE static Object *createUint8TypedArray(uint8_t *bytes, size_t byteLength); enum class TypedArrayType { @@ -119,47 +120,47 @@ public: static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength); /** - * @brief Creates a JavaScript Array Buffer object from an existing pointer. - * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. - * @param[in] byteLength The number of bytes pointed to by the parameter bytes. - * @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error. - * @note The return value (non-null) has to be released manually. - */ + * @brief Creates a JavaScript Array Buffer object from an existing pointer. + * @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object. + * @param[in] byteLength The number of bytes pointed to by the parameter bytes. + * @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object *createArrayBufferObject(const void *data, size_t byteLength); using BufferContentsFreeFunc = void (*)(void *contents, size_t byteLength, void *userData); static Object *createExternalArrayBufferObject(void *contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void *freeUserData = nullptr); /** - * @brief Creates a JavaScript Object from a JSON formatted string. - * @param[in] jsonStr The utf-8 string containing the JSON string to be parsed. - * @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid. - * @note The return value (non-null) has to be released manually. - */ + * @brief Creates a JavaScript Object from a JSON formatted string. + * @param[in] jsonStr The utf-8 string containing the JSON string to be parsed. + * @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid. + * @note The return value (non-null) has to be released manually. + */ static Object *createJSONObject(const ccstd::string &jsonStr); /** - * @brief Creates a JavaScript Native Binding Object from an existing se::Class instance. - * @param[in] cls The se::Class instance which stores native callback informations. - * @return A JavaScript Native Binding Object, or nullptr if there is an error. - * @note The return value (non-null) has to be released manually. - */ + * @brief Creates a JavaScript Native Binding Object from an existing se::Class instance. + * @param[in] cls The se::Class instance which stores native callback informations. + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object *createObjectWithClass(Class *cls); /** - * @brief Gets a se::Object from an existing native object pointer. - * @param[in] ptr The native object pointer associated with the se::Object - * @return A JavaScript Native Binding Object, or nullptr if there is an error. - * @note The return value (non-null) has to be released manually. - */ + * @brief Gets a se::Object from an existing native object pointer. + * @param[in] ptr The native object pointer associated with the se::Object + * @return A JavaScript Native Binding Object, or nullptr if there is an error. + * @note The return value (non-null) has to be released manually. + */ static Object *getObjectWithPtr(void *ptr); /** - * @brief Gets a property from an object. - * @param[in] name A utf-8 string containing the property's name. - * @param[out] value The property's value if object has the property, otherwise the undefined value. - * @return true if object has the property, otherwise false. - */ + * @brief Gets a property from an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[out] value The property's value if object has the property, otherwise the undefined value. + * @return true if object has the property, otherwise false. + */ inline bool getProperty(const char *name, Value *data) { return getProperty(name, data, false); } @@ -171,11 +172,11 @@ public: } /** - * @brief Sets a property to an object. - * @param[in] name A utf-8 string containing the property's name. - * @param[in] value A value to be used as the property's value. - * @return true if the property is set successfully, otherwise false. - */ + * @brief Sets a property to an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] value A value to be used as the property's value. + * @return true if the property is set successfully, otherwise false. + */ bool setProperty(const char *name, const Value &data); inline bool setProperty(const ccstd::string &name, const Value &value) { @@ -183,119 +184,119 @@ public: } /** - * @brief Delete a property of an object. - * @param[in] name A utf-8 string containing the property's name. - * @return true if the property is deleted successfully, otherwise false. - */ + * @brief Delete a property of an object. + * @param[in] name A utf-8 string containing the property's name. + * @return true if the property is deleted successfully, otherwise false. + */ bool deleteProperty(const char *name); /** - * @brief Defines a property with native accessor callbacks for an object. - * @param[in] name A utf-8 string containing the property's name. - * @param[in] getter The native callback for getter. - * @param[in] setter The native callback for setter. - * @return true if succeed, otherwise false. - */ + * @brief Defines a property with native accessor callbacks for an object. + * @param[in] name A utf-8 string containing the property's name. + * @param[in] getter The native callback for getter. + * @param[in] setter The native callback for setter. + * @return true if succeed, otherwise false. + */ bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter); bool defineOwnProperty(const char *name, const se::Value &value, bool writable = true, bool enumerable = true, bool configurable = true); /** - * @brief Defines a function with a native callback for an object. - * @param[in] funcName A utf-8 string containing the function name. - * @param[in] func The native callback triggered by JavaScript code. - * @return true if succeed, otherwise false. - */ + * @brief Defines a function with a native callback for an object. + * @param[in] funcName A utf-8 string containing the function name. + * @param[in] func The native callback triggered by JavaScript code. + * @return true if succeed, otherwise false. + */ bool defineFunction(const char *funcName, v8::FunctionCallback func); /** - * @brief Tests whether an object can be called as a function. - * @return true if object can be called as a function, otherwise false. - */ + * @brief Tests whether an object can be called as a function. + * @return true if object can be called as a function, otherwise false. + */ bool isFunction() const; /** - * @brief Calls an object as a function. - * @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0. - * @param[in] thisObject The object to use as "this," or NULL to use the global object as "this." - * @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored. - * @return true if object is a function and there isn't any errors, otherwise false. - */ + * @brief Calls an object as a function. + * @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0. + * @param[in] thisObject The object to use as "this," or NULL to use the global object as "this." + * @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored. + * @return true if object is a function and there isn't any errors, otherwise false. + */ bool call(const ValueArray &args, Object *thisObject, Value *rval = nullptr); /** - * @brief Tests whether an object is an array. - * @return true if object is an array, otherwise false. - */ + * @brief Tests whether an object is an array. + * @return true if object is an array, otherwise false. + */ bool isArray() const; /** - * @brief Gets array length of an array object. - * @param[out] length The array length to be stored. It's set to 0 if there is an error. - * @return true if succeed, otherwise false. - */ + * @brief Gets array length of an array object. + * @param[out] length The array length to be stored. It's set to 0 if there is an error. + * @return true if succeed, otherwise false. + */ bool getArrayLength(uint32_t *length) const; /** - * @brief Gets an element from an array object by numeric index. - * @param[in] index An integer value for index. - * @param[out] data The se::Value to be stored for the element in certain index. - * @return true if succeed, otherwise false. - */ + * @brief Gets an element from an array object by numeric index. + * @param[in] index An integer value for index. + * @param[out] data The se::Value to be stored for the element in certain index. + * @return true if succeed, otherwise false. + */ bool getArrayElement(uint32_t index, Value *data) const; /** - * @brief Sets an element to an array object by numeric index. - * @param[in] index An integer value for index. - * @param[in] data The se::Value to be set to array with certain index. - * @return true if succeed, otherwise false. - */ + * @brief Sets an element to an array object by numeric index. + * @param[in] index An integer value for index. + * @param[in] data The se::Value to be set to array with certain index. + * @return true if succeed, otherwise false. + */ bool setArrayElement(uint32_t index, const Value &data); /** @brief Tests whether an object is a typed array. - * @return true if object is a typed array, otherwise false. - */ + * @return true if object is a typed array, otherwise false. + */ bool isTypedArray() const; /** - * @brief Gets the type of a typed array object. - * @return The type of a typed array object. - */ + * @brief Gets the type of a typed array object. + * @return The type of a typed array object. + */ TypedArrayType getTypedArrayType() const; /** - * @brief Gets backing store of a typed array object. - * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. - * @param[out] length The byte length of a JavaScript Typed Array object. - * @return true if succeed, otherwise false. - */ + * @brief Gets backing store of a typed array object. + * @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object. + * @param[out] length The byte length of a JavaScript Typed Array object. + * @return true if succeed, otherwise false. + */ bool getTypedArrayData(uint8_t **ptr, size_t *length) const; /** - * @brief Tests whether an object is an array buffer object. - * @return true if object is an array buffer object, otherwise false. - */ + * @brief Tests whether an object is an array buffer object. + * @return true if object is an array buffer object, otherwise false. + */ bool isArrayBuffer() const; /** - * @brief Gets buffer data of an array buffer object. - * @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object. - * @param[out] length The number of bytes in a JavaScript data object. - * @return true if succeed, otherwise false. - */ + * @brief Gets buffer data of an array buffer object. + * @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object. + * @param[out] length The number of bytes in a JavaScript data object. + * @return true if succeed, otherwise false. + */ bool getArrayBufferData(uint8_t **ptr, size_t *length) const; /** - * @brief Gets all property names of an object. - * @param[out] allKeys A string vector to store all property names. - * @return true if succeed, otherwise false. - */ + * @brief Gets all property names of an object. + * @param[out] allKeys A string vector to store all property names. + * @return true if succeed, otherwise false. + */ bool getAllKeys(ccstd::vector *allKeys) const; void setPrivateObject(PrivateObjectBase *data); PrivateObjectBase *getPrivateObject() const; - /** + /* * @brief Gets an object's private data. * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. */ @@ -304,7 +305,14 @@ public: } /** - * @brief Sets a pointer to private data on an object. + * @brief Sets a pointer to private data on an object and use smart pointer to hold it. + * + * If the pointer is an instance of `cc::RefCounted`, an `cc::IntrusivePtr` will be created to hold + * the reference to the object, otherwise a `std::shared_ptr` object will be used. + * When the JS object is freed by GC, the corresponding smart pointer `IntrusivePtr/shared_ptr` will also be destroyed. + * + * If you do not want the pointer to be released by GC, you can call `setRawPrivateData`. + * * @param[in] data A void* to set as the object's private data. * @note This method will associate private data with se::Object by ccstd::unordered_map::emplace. * It's used for search a se::Object via a void* private data. @@ -315,6 +323,69 @@ public: setPrivateObject(se::make_shared_private_object(data)); } + /** + * @brief Use a InstrusivePtr to hold private data on the se::Object. + * + * @tparam T + * @param data A intrusive pointer object + */ + template + inline void setPrivateData(const cc::IntrusivePtr &data) { + setPrivateObject(se::ccintrusive_ptr_private_object(data)); + } + + /** + * @brief Use a std::shared_ptr to hold private data on the se::Object. + * + * @tparam T + * @param data A shared_ptr object + */ + template + inline void setPrivateData(const std::shared_ptr &data) { + setPrivateObject(se::shared_ptr_private_object(data)); + } + + /** + * @brief Set pointer to the private data on an object and will not use smart pointer to hold it. + * + * @tparam T + * @param data + * @param tryDestroyInGC When GCing the JS object, whether to `delete` the `data` pointer. + */ + template + inline void setRawPrivateData(T *data, bool tryDestroyInGC = false) { + static_assert(!std::is_void::value, "void * is not allowed for private data"); + auto *privateObject = se::rawref_private_object(data); + if (tryDestroyInGC) { + privateObject->tryAllowDestroyInGC(); + } + setPrivateObject(privateObject); + } + + /** + * @brief Get the underlying private data as std::shared_ptr + * + * @tparam T + * @return std::shared_ptr + */ + template + inline std::shared_ptr getPrivateSharedPtr() const { + assert(_privateObject->isSharedPtr()); + return static_cast *>(_privateObject)->getData(); + } + + /** + * @brief Get the underlying private data as InstrusivePtr + * + * @tparam T + * @return cc::IntrusivePtr + */ + template + inline cc::IntrusivePtr getPrivateInstrusivePtr() const { + assert(_privateObject->isCCIntrusivePtr()); + return static_cast *>(_privateObject)->getData(); + } + template inline T *getTypedPrivateData() const { return reinterpret_cast(getPrivateData()); @@ -332,29 +403,29 @@ public: void setClearMappingInFinalizer(bool v) { _clearMappingInFinalizer = v; } /** - * @brief Roots an object from garbage collection. - * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. - * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. - */ + * @brief Roots an object from garbage collection. + * @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it. + * An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void root(); /** - * @brief Unroots an object from garbage collection. - * @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. - */ + * @brief Unroots an object from garbage collection. + * @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection. + */ void unroot(); /** - * @brief Tests whether an object is rooted. - * @return true if it has been already rooted, otherwise false. - */ + * @brief Tests whether an object is rooted. + * @return true if it has been already rooted, otherwise false. + */ bool isRooted() const; /** - * @brief Tests whether two objects are strict equal, as compared by the JS === operator. - * @param[in] o The object to be tested with this object. - * @return true if the two values are strict equal, otherwise false. - */ + * @brief Tests whether two objects are strict equal, as compared by the JS === operator. + * @param[in] o The object to be tested with this object. + * @return true if the two values are strict equal, otherwise false. + */ bool strictEquals(Object *o) const; /** @@ -410,17 +481,17 @@ public: bool attachObject(Object *obj); /** - * @brief Detaches an object from current object. - * @param[in] obj The object to be detached. - * @return true if succeed, otherwise false. - * @note The attached object will not be released if current object is not garbage collected. - */ + * @brief Detaches an object from current object. + * @param[in] obj The object to be detached. + * @return true if succeed, otherwise false. + * @note The attached object will not be released if current object is not garbage collected. + */ bool detachObject(Object *obj); /** - * @brief Returns the string for describing current object. - * @return The string for describing current object. - */ + * @brief Returns the string for describing current object. + * @return The string for describing current object. + */ ccstd::string toString() const; ccstd::string toStringExt() const; diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index a8b58f674c..5d46ab8396 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -323,20 +323,18 @@ bool seval_to_Map_string_key(const se::Value &v, cc::RefMap *r return true; } -template -inline typename std::enable_if::value, void>::type -cc_tmp_set_private_data(se::Object *obj, T *v) { // NOLINT(readability-identifier-naming) - obj->setPrivateData(v); +template +void cc_tmp_set_private_data(se::Object *obj, T *v) { // NOLINT(readability-identifier-naming) + if constexpr (std::is_base_of_v) { + obj->setPrivateData(v); + }else{ + obj->setRawPrivateData(v); + } + } -template -inline typename std::enable_if::value, void>::type -cc_tmp_set_private_data(se::Object *obj, T *v) { // NOLINT(readability-identifier-naming) - obj->setPrivateObject(se::rawref_private_object(v)); -} - -inline void cc_tmp_set_private_data(se::Object *obj, cc::gfx::Sampler *v) { - obj->setPrivateObject(se::rawref_private_object(v)); +inline void cc_tmp_set_private_data(se::Object *obj, cc::gfx::Sampler *v) { // NOLINT(readability-identifier-naming) + obj->setRawPrivateData(v); } //handle reference @@ -392,7 +390,7 @@ bool native_ptr_to_rooted_seval( // NOLINT(readability-identifier-naming) CC_ASSERT(cls != nullptr); obj = se::Object::createObjectWithClass(cls); obj->root(); - obj->setPrivateObject(se::rawref_private_object(v)); + obj->setRawPrivateData(v); if (isReturnCachedValue != nullptr) { *isReturnCachedValue = false; } @@ -1080,9 +1078,7 @@ bool sevalue_to_native(const se::Value &from, std::shared_ptr *out, se::Objec out->reset(); return true; } - auto *privateObject = from.toObject()->getPrivateObject(); - CC_ASSERT(privateObject->isSharedPtr()); - *out = static_cast*>(privateObject)->share(); + *out = from.toObject()->getPrivateSharedPtr(); return true; } @@ -1100,17 +1096,7 @@ bool sevalue_to_native(const se::Value &from, cc::IntrusivePtr *to, se::Objec to = nullptr; return true; } - - auto *privateObject = from.toObject()->getPrivateObject(); - if (!privateObject) { - T *tmp = nullptr; - bool ok = sevalue_to_native(from, &tmp, ctx); - *to = tmp; - return ok; - } - - CC_ASSERT(privateObject->isCCShared()); - *to = static_cast *>(privateObject)->ccShared(); + *to = from.toObject()->getPrivateInstrusivePtr(); return true; } @@ -1222,12 +1208,12 @@ template inline bool nativevalue_to_se(const ccstd::vector &from, se::Value &to, se::Object *ctx); // NOLINT template -inline bool nativevalue_to_se(const ccstd::vector *from, se::Value &to, se::Object *ctx) { +inline bool nativevalue_to_se(const ccstd::vector *from, se::Value &to, se::Object *ctx) { // NOLINT return nativevalue_to_se(*from, to, ctx); } template -inline bool nativevalue_to_se(ccstd::vector *const from, se::Value &to, se::Object *ctx) { +inline bool nativevalue_to_se(ccstd::vector *const from, se::Value &to, se::Object *ctx) { // NOLINT return nativevalue_to_se(*from, to, ctx); } @@ -1564,7 +1550,8 @@ inline bool nativevalue_to_se(const std::shared_ptr &from, se::Value &to, se: CC_ASSERT(cls); se::Object *obj = se::Object::createObjectWithClass(cls); to.setObject(obj, true); - obj->setPrivateObject(se::shared_private_object(from)); + obj->setPrivateData(from); + } else { to.setObject(it->second); } @@ -1585,7 +1572,7 @@ inline bool nativevalue_to_se(const cc::IntrusivePtr &from, se::Value &to, se CC_ASSERT(cls); se::Object *obj = se::Object::createObjectWithClass(cls); to.setObject(obj, true); - obj->setPrivateObject(se::ccshared_private_object(from)); + obj->setPrivateData(from); } else { to.setObject(it->second); } diff --git a/native/cocos/bindings/manual/jsb_global.h b/native/cocos/bindings/manual/jsb_global.h index c9e5be4a7c..4d934739af 100644 --- a/native/cocos/bindings/manual/jsb_global.h +++ b/native/cocos/bindings/manual/jsb_global.h @@ -29,28 +29,24 @@ #include "jsb_global_init.h" template -T *jsb_override_new(Args &&...args) { //NOLINT(readability-identifier-naming) - //create object in the default way +T *jsb_override_new(Args &&...args) { // NOLINT(readability-identifier-naming) + // create object in the default way return ccnew T(std::forward(args)...); } template -void jsb_override_delete(T *arg) { //NOLINT(readability-identifier-naming) - //create object in gfx way +void jsb_override_delete(T *arg) { // NOLINT(readability-identifier-naming) + // create object in gfx way delete (arg); } template -typename std::enable_if::value, se::PrivateObjectBase *>::type -jsb_make_private_object(ARGS &&...args) { //NOLINT(readability-identifier-naming) - //return se::raw_private_data(ccnew T(std::forward(args)...)); - return se::ccshared_private_object(ccnew T(std::forward(args)...)); -} - -template -typename std::enable_if::value, se::PrivateObjectBase *>::type -jsb_make_private_object(ARGS &&...args) { //NOLINT(readability-identifier-naming) - return se::shared_private_object(std::make_shared(std::forward(args)...)); +se::PrivateObjectBase *jsb_make_private_object(ARGS &&...args) { // NOLINT(readability-identifier-naming) + if constexpr (std::is_base_of::value) { + return se::ccintrusive_ptr_private_object(ccnew T(std::forward(args)...)); + } else { + return se::shared_ptr_private_object(std::make_shared(std::forward(args)...)); + } } #define JSB_MAKE_PRIVATE_OBJECT(kls, ...) jsb_make_private_object(__VA_ARGS__) @@ -61,10 +57,10 @@ class Class; class Value; } // namespace se -bool jsb_register_global_variables(se::Object *global); //NOLINT(readability-identifier-naming) +bool jsb_register_global_variables(se::Object *global); // NOLINT(readability-identifier-naming) -bool jsb_set_extend_property(const char *ns, const char *clsName); //NOLINT(readability-identifier-naming) -bool jsb_run_script(const ccstd::string &filePath, se::Value *rval = nullptr); //NOLINT(readability-identifier-naming) -bool jsb_run_script_module(const ccstd::string &filePath, se::Value *rval = nullptr); //NOLINT(readability-identifier-naming) +bool jsb_set_extend_property(const char *ns, const char *clsName); // NOLINT(readability-identifier-naming) +bool jsb_run_script(const ccstd::string &filePath, se::Value *rval = nullptr); // NOLINT(readability-identifier-naming) +bool jsb_run_script_module(const ccstd::string &filePath, se::Value *rval = nullptr); // NOLINT(readability-identifier-naming) -bool jsb_global_load_image(const ccstd::string &path, const se::Value &callbackVal); //NOLINT(readability-identifier-naming) +bool jsb_global_load_image(const ccstd::string &path, const se::Value &callbackVal); // NOLINT(readability-identifier-naming) From 2bd62354a7841fb50985debfab44e6ec4cdcfd7f Mon Sep 17 00:00:00 2001 From: timlyeee <43355299+timlyeee@users.noreply.github.com> Date: Wed, 24 Aug 2022 17:42:47 +0800 Subject: [PATCH 04/73] V3.6.1 save image data (#12503) --- cocos/native-binding/impl.ts | 13 ++ cocos/native-binding/index.ts | 33 ++++ native/cocos/bindings/manual/jsb_global.cpp | 62 ++++++ native/cocos/platform/Image.cpp | 186 +++++++++++++++++- native/cocos/platform/Image.h | 12 +- .../cocos/platform/win32/modules/System.cpp | 6 +- 6 files changed, 307 insertions(+), 5 deletions(-) diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 1b95baf61d..290976ec13 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -124,6 +124,18 @@ if( NATIVE ){ globalJsb.__JsbBridgeWrapper = value; }, }); + const originSaveImageData = globalJsb.saveImageData; + globalJsb.saveImageData = (data: Uint8Array, width: number, height: number, filePath: string) => { + return new Promise((resolve, reject) => { + originSaveImageData(data, width, height, filePath, (isSuccess) => { + if (isSuccess) { + resolve(); + } else { + reject(); + } + }) + }); + } } export const native = { @@ -140,4 +152,5 @@ export const native = { AssetsManager: globalJsb.AssetsManager, EventAssetsManager: globalJsb.EventAssetsManager, Manifest: globalJsb.Manifest, + saveImageData: globalJsb.saveImageData, }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index 1daf159025..e162d4a357 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -1316,4 +1316,37 @@ export declare namespace native { */ export function removeAllListeners(); } + /** + * @en Save the image to the path indicated. + * @zh 保存图片到指定路径。 + * @param data : @en the image data, should be raw data array with uint8 @zh 图片数据, 应为原始数据数组,uint8 格式。 + * @param path : @en the path to save @zh 保存路径 + * @param width : @en the width of the image @zh 图片宽度 + * @param height : @en the height of the image @zh 图片高度 + * @param filePath : @en the file path of the image @zh 图片文件路径 + * @param callback : @en the callback function @zh 回调函数 + * @example + * ```ts + let renderTexture = new RenderTexture(); + let renderWindowInfo = { + width: this._width, + height: this._height + }; + renderTexture.reset(renderWindowInfo); + cameras.forEach((camera: any) => { + camera.targetTexture = renderTexture; + }); + await this.waitForNextFrame(); + cameras.forEach((camera: any) => { + camera.targetTexture = null; + }); + let pixelData = renderTexture.readPixels(); + jsb.saveImageData(pixelData, path, width, height, filePath, (isSuccess) => { + if (isSuccess) { + console.log('save image success'); + } else { + console.log('save image failed'); + })); + */ + export function saveImageData(data: Uint8Array, width: number, height: number, filePath: string): Promise; } diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index 1de97edfa2..8f57a533c9 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -25,6 +25,7 @@ #include "jsb_global.h" #include "application/ApplicationManager.h" +#include "base/Data.h" #include "base/DeferredReleasePool.h" #include "base/Scheduler.h" #include "base/ThreadPool.h" @@ -659,7 +660,67 @@ static bool js_loadImage(se::State &s) { // NOLINT return false; } SE_BIND_FUNC(js_loadImage) +//pixels(RGBA), width, height, fullFilePath(*.png/*.jpg) +static bool js_saveImageData(se::State& s) { // NOLINT + const auto& args = s.args(); + size_t argc = args.size(); + bool ok = true;// NOLINT(readability-identifier-length) + if (argc == 4 || argc == 5) { + auto *uint8ArrayObj = args[0].toObject(); + uint8_t *uint8ArrayData {nullptr}; + size_t length = 0; + uint8ArrayObj->root(); + uint8ArrayObj->incRef(); + uint8ArrayObj->getTypedArrayData(&uint8ArrayData, &length); + uint32_t width; + uint32_t height; + ok &= sevalue_to_native(args[1], &width); + ok &= sevalue_to_native(args[2], &height); + std::string filePath; + ok &= sevalue_to_native(args[3], &filePath); + SE_PRECONDITION2(ok, false, "js_saveImageData : Error processing arguments"); + + se::Value callbackVal = argc == 5 ? args[4] : se::Value::Null; + se::Object *callbackObj {nullptr}; + if (!callbackVal.isNull()) { + CC_ASSERT(callbackVal.isObject()); + CC_ASSERT(callbackVal.toObject()->isFunction()); + callbackObj = callbackVal.toObject(); + callbackObj->root(); + callbackObj->incRef(); + } + + gThreadPool->pushTask([=](int /*tid*/) { + // isToRGB = false, to keep alpha channel + auto *img = ccnew Image(); + // A conversion from size_t to uint32_t might lose integer precision + img->initWithRawData(uint8ArrayData, static_cast(length), width, height, 32 /*Unused*/); + bool isSuccess = img->saveToFile(filePath, false/*isToRGB*/); + CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread([=]() { + se::AutoHandleScope hs; + se::ValueArray seArgs; + + se::Value isSuccessVal; + nativevalue_to_se(isSuccess, isSuccessVal); + + seArgs.push_back(isSuccessVal); + if (callbackObj) { + callbackObj->call(seArgs, nullptr); + callbackObj->unroot(); + callbackObj->decRef(); + } + uint8ArrayObj->unroot(); + uint8ArrayObj->decRef(); + delete img; + }); + }); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d or %d", (int)argc, 4, 5); + return false; +} +SE_BIND_FUNC(js_saveImageData) static bool js_destroyImage(se::State &s) { // NOLINT const auto &args = s.args(); size_t argc = args.size(); @@ -1313,6 +1374,7 @@ bool jsb_register_global_variables(se::Object *global) { // NOLINT __jsbObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap)); __jsbObj->defineFunction("loadImage", _SE(js_loadImage)); + __jsbObj->defineFunction("saveImageData", _SE(js_saveImageData)); __jsbObj->defineFunction("openURL", _SE(JSB_openURL)); __jsbObj->defineFunction("copyTextToClipboard", _SE(JSB_copyTextToClipboard)); __jsbObj->defineFunction("setPreferredFramesPerSecond", _SE(JSB_setPreferredFramesPerSecond)); diff --git a/native/cocos/platform/Image.cpp b/native/cocos/platform/Image.cpp index 3194899320..b33c9a5c36 100644 --- a/native/cocos/platform/Image.cpp +++ b/native/cocos/platform/Image.cpp @@ -30,6 +30,7 @@ #include #include "base/Config.h" // CC_USE_JPEG, CC_USE_WEBP #include "base/std/container/string.h" +#include "gfx-base/GFXDef-common.h" #if CC_USE_JPEG #include "jpeg/jpeglib.h" @@ -288,7 +289,6 @@ bool Image::initWithImageFile(const ccstd::string &path) { bool Image::initWithImageData(const unsigned char *data, uint32_t dataLen) { bool ret = false; - do { CC_BREAK_IF(!data || dataLen <= 0); @@ -944,4 +944,188 @@ bool Image::initWithRawData(const unsigned char *data, uint32_t /*dataLen*/, int return ret; } +bool Image::saveToFile(const std::string& filename, bool isToRGB) { + //only support for Image::PixelFormat::RGB888 or Image::PixelFormat::RGBA8888 uncompressed data + if (isCompressed() || (_renderFormat != gfx::Format::RGB8 && _renderFormat != gfx::Format::RGBA8)) { + CC_LOG_DEBUG("saveToFile: Image: saveToFile is only support for gfx::Format::RGB8 or gfx::Format::RGBA8 uncompressed data for now"); + return false; + } + + std::string fileExtension = FileUtils::getInstance()->getFileExtension(filename); + + if (fileExtension == ".png") { + return saveImageToPNG(filename, isToRGB); + } + if (fileExtension == ".jpg") { + return saveImageToJPG(filename); + } + CC_LOG_DEBUG("saveToFile: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str()); + return false; +} + + +bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB) { + bool ret = false; + + FILE *fp{nullptr}; + png_structp pngPtr{nullptr}; + png_infop infoPtr{nullptr}; + png_colorp palette{nullptr}; + png_bytep *rowPointers{nullptr}; + bool hasAlpha = gfx::GFX_FORMAT_INFOS[static_cast(_renderFormat)].hasAlpha; + do { + // Init png structure and png ptr + pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + CC_BREAK_IF(!pngPtr); + if (setjmp(png_jmpbuf(pngPtr))) { + break; + } + infoPtr = png_create_info_struct(pngPtr); + CC_BREAK_IF(!infoPtr); + // Start open file + fp = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb"); + CC_BREAK_IF(!fp); + png_init_io(pngPtr, fp); + auto mask = (!isToRGB && hasAlpha) ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB; + png_set_IHDR(pngPtr, infoPtr, _width, _height, 8, mask, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + + palette = static_cast(png_malloc(pngPtr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color))); + CC_BREAK_IF(!palette); + png_set_PLTE(pngPtr, infoPtr, palette, PNG_MAX_PALETTE_LENGTH); + + png_write_info(pngPtr, infoPtr); + + png_set_packing(pngPtr); + + //row_pointers = (png_bytep *)png_malloc(png_ptr, _height * sizeof(png_bytep)); + rowPointers = static_cast(CC_MALLOC(_height * sizeof(png_bytep))); + CC_BREAK_IF(!rowPointers); + + if (!hasAlpha) { + for (int i = 0; i < _height; i++) { + rowPointers[i] = static_cast(_data) + i * _width * 3; + } + png_write_image(pngPtr, rowPointers); + } else { + if (isToRGB) { + auto *tempData = static_cast(CC_MALLOC(_width * _height * 3 * sizeof(unsigned char))); + if (nullptr == tempData) { + break; + } + auto *dst = tempData; + auto *src = _data; + for (int t = 0; t < _width * _height; t++) { + memcpy(dst, src, 3); + dst += 3; + src += 4; + } + + for (int i = 0; i < _height; i++) { + rowPointers[i] = static_cast(tempData) + i * _width * 3; + } + if (tempData != nullptr) { + CC_FREE(tempData); + } + png_write_image(pngPtr, rowPointers); + } else { + for (int i = 0; i < _height; i++) { + rowPointers[i] = static_cast(_data) + i * _width * 4 /*Bytes per pixel*/; + } + png_write_image(pngPtr, rowPointers); + } + } + + png_write_end(pngPtr, infoPtr); + ret = true; + } while (false); + + /*Later free for all functions*/ + if (rowPointers) { + free(rowPointers); + rowPointers = nullptr; + } + if (palette) { + png_free(pngPtr, palette); + } + if (infoPtr) { + png_destroy_write_struct(&pngPtr, &infoPtr); + } + if (fp) { + fclose(fp); + } + if (pngPtr) { + png_destroy_write_struct(&pngPtr, nullptr); + } + return ret; +} + +bool Image::saveImageToJPG(const std::string& filePath) { + bool ret = false; + do { + struct jpeg_compress_struct cinfo; + struct jpeg_error_mgr jerr; + FILE * outfile; /* target file */ + JSAMPROW rowPointer[1]; /* pointer to JSAMPLE row[s] */ + int rowStride; /* physical row width in image buffer */ + + cinfo.err = jpeg_std_error(&jerr); + /* Now we can initialize the JPEG compression object. */ + jpeg_create_compress(&cinfo); + + CC_BREAK_IF((outfile = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb")) == nullptr); + + jpeg_stdio_dest(&cinfo, outfile); + + cinfo.image_width = _width; /* image width and height, in pixels */ + cinfo.image_height = _height; + cinfo.input_components = 3; /* # of color components per pixel */ + cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, 90, TRUE); + + jpeg_start_compress(&cinfo, TRUE); + + rowStride = _width * 3; /* JSAMPLEs per row in image_buffer */ + bool hasAlpha = gfx::GFX_FORMAT_INFOS[static_cast(_renderFormat)].hasAlpha; + + if (hasAlpha) { + auto *tempData = static_cast(CC_MALLOC(_width * _height * 3 * sizeof(unsigned char))); + if (nullptr == tempData) { + jpeg_finish_compress(&cinfo); + jpeg_destroy_compress(&cinfo); + fclose(outfile); + break; + } + auto *dst = tempData; + auto *src = _data; + for (int t = 0; t < _width * _height; t++) { + memcpy(dst, src, 3); + dst += 3; + src += 4; + } + while (cinfo.next_scanline < cinfo.image_height) { + rowPointer[0] = & tempData[cinfo.next_scanline * rowStride]; + (void) jpeg_write_scanlines(&cinfo, rowPointer, 1); + } + if (tempData != nullptr) { + CC_FREE(tempData); + } + } else { + while (cinfo.next_scanline < cinfo.image_height) { + rowPointer[0] = & _data[cinfo.next_scanline * rowStride]; + (void) jpeg_write_scanlines(&cinfo, rowPointer, 1); + } + } + + jpeg_finish_compress(&cinfo); + fclose(outfile); + jpeg_destroy_compress(&cinfo); + + ret = true; + } while (false); + return ret; +} + } // namespace cc diff --git a/native/cocos/platform/Image.h b/native/cocos/platform/Image.h index 497f5f6f55..8b0605e0e4 100644 --- a/native/cocos/platform/Image.h +++ b/native/cocos/platform/Image.h @@ -80,9 +80,16 @@ public: inline int getWidth() const { return _width; } inline int getHeight() const { return _height; } inline ccstd::string getFilePath() const { return _filePath; } - inline bool isCompressed() const { return _isCompressed; } + /** + @brief Save Image data to the specified file, with specified format. + @param filename the file's absolute path, including file suffix. + @param isToRGB whether the image is saved as RGB format. + */ + bool saveToFile(const std::string &filename, bool isToRGB = true); + + protected: bool initWithJpgData(const unsigned char *data, uint32_t dataLen); bool initWithPngData(const unsigned char *data, uint32_t dataLen); @@ -96,6 +103,9 @@ protected: bool initWithETC2Data(const unsigned char *data, uint32_t dataLen); bool initWithASTCData(const unsigned char *data, uint32_t dataLen); + bool saveImageToPNG(const std::string& filePath, bool isToRGB = true); + bool saveImageToJPG(const std::string& filePath); + unsigned char *_data = nullptr; uint32_t _dataLen = 0; int _width = 0; diff --git a/native/cocos/platform/win32/modules/System.cpp b/native/cocos/platform/win32/modules/System.cpp index e82bb49888..ed9f803638 100644 --- a/native/cocos/platform/win32/modules/System.cpp +++ b/native/cocos/platform/win32/modules/System.cpp @@ -112,10 +112,10 @@ ccstd::string System::getCurrentLanguageCode() const { const LCID locale_id = MAKELCID(lid, SORT_DEFAULT); int length = GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, nullptr, 0); - char *tempCode = ccnew char[length]; + char *tempCode = reinterpret_cast(CC_MALLOC(length)); GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, tempCode, length); - ccstd::string code = tempCode; - delete tempCode; + ccstd::string code(tempCode); + CC_FREE(tempCode); return code; } From a32569741fbaf29eb0343cac412a4a8e070a79b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 25 Aug 2022 11:51:09 +0800 Subject: [PATCH 05/73] 3.6.1 Android dont link unused libraries (#12537) * Update external-config.json * enable flags in engine --- native/cmake/predefine.cmake | 16 ++++++++++++++++ native/external-config.json | 2 +- .../utils/generate_compile_commands_android.sh | 5 ++--- templates/cmake/android.cmake | 15 --------------- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index f1e2509727..a7241af001 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -132,6 +132,22 @@ else() message(STATUS "Ignore NO_WERROR") endif() +if(ANDROID) + if("${ANDROID_ABI}" STREQUAL "armeabi-v7a") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon-fp16") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon-fp16") + endif() + + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing -frtti -fexceptions") + + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") + if(NOT DEFINED HIDE_SYMBOLS OR HIDE_SYMBOLS) # hidden by default + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -fvisibility=hidden") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden -fvisibility-inlines-hidden") + endif() +endif() function(cc_enable_werror source_list) foreach(src IN LISTS source_list) diff --git a/native/external-config.json b/native/external-config.json index abc1656a3c..2dbd568bc7 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3d-gfx-130" + "checkout": "v3.6.1-1" } } diff --git a/native/utils/generate_compile_commands_android.sh b/native/utils/generate_compile_commands_android.sh index 7d156c0cc9..a1a482aedc 100755 --- a/native/utils/generate_compile_commands_android.sh +++ b/native/utils/generate_compile_commands_android.sh @@ -28,8 +28,7 @@ cmake -Sbuild -Bbuild -DCC_USE_GLES2=ON -DCC_USE_VULKAN=ON -DCC_USE_GLES3=ON \ -DCMAKE_TOOLCHAIN_FILE="$ndk_path/build/cmake/android.toolchain.cmake" \ -DANDROID_PLATFORM=android-21 \ -DCMAKE_BUILD_TYPE=Debug \ - -DCMAKE_C_FLAGS="-mfpu=neon-fp16" \ - -DCMAKE_CXX_FLAGS="-mfpu=neon-fp16" \ + -DANDROID_ABI=arm64-v8a \ -G "$GENERATER" $MAKE_BIN -cp build/compile_commands.json . \ No newline at end of file +cp build/compile_commands.json . diff --git a/templates/cmake/android.cmake b/templates/cmake/android.cmake index 7d5b198f98..9b0da43012 100644 --- a/templates/cmake/android.cmake +++ b/templates/cmake/android.cmake @@ -2,21 +2,6 @@ macro(cc_android_before_target target_name) list(APPEND CC_ALL_SOURCES ${CC_COMMON_SOURCES} ${CC_PROJ_SOURCES}) - - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsigned-char -ffunction-sections -fdata-sections -fstrict-aliasing -frtti -fexceptions") - - if("${ANDROID_ABI}" STREQUAL "armeabi-v7a") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon-fp16") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon-fp16") - endif() - - set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") - set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fvisibility=default -fno-omit-frame-pointer") - if(NOT DEFINED HIDE_SYMBOLS OR HIDE_SYMBOLS) # hidden by default - set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -fvisibility=hidden") - set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden -fvisibility-inlines-hidden") - endif() cc_common_before_target(${target_name}) endmacro() From f5ac35997a0f55285a4cd62448e507de67e42e33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 25 Aug 2022 11:54:49 +0800 Subject: [PATCH 06/73] dont overwrite ios launchscreen on build (#12527) --- templates/cmake/apple.cmake | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/templates/cmake/apple.cmake b/templates/cmake/apple.cmake index 966fb38845..29495d6433 100644 --- a/templates/cmake/apple.cmake +++ b/templates/cmake/apple.cmake @@ -8,10 +8,12 @@ macro(cc_ios_before_target target_name) list(APPEND CC_PROJ_SOURCES ${CC_UI_RESOURCES} ) - if (USE_PORTRAIT) - configure_file(${CC_PROJECT_DIR}/LaunchScreenBackgroundPortrait.png ${CC_PROJECT_DIR}/LaunchScreenBackground.png COPYONLY) - else() - configure_file(${CC_PROJECT_DIR}/LaunchScreenBackgroundLandscape.png ${CC_PROJECT_DIR}/LaunchScreenBackground.png COPYONLY) + if(NOT EXISTS ${CC_PROJECT_DIR}/LaunchScreenBackground.png) + if (USE_PORTRAIT) + configure_file(${CC_PROJECT_DIR}/LaunchScreenBackgroundPortrait.png ${CC_PROJECT_DIR}/LaunchScreenBackground.png COPYONLY) + else() + configure_file(${CC_PROJECT_DIR}/LaunchScreenBackgroundLandscape.png ${CC_PROJECT_DIR}/LaunchScreenBackground.png COPYONLY) + endif() endif() if(NOT CUSTOM_COPY_RESOURCE_HOOK) cc_include_resources(${RES_DIR}/data CC_ASSET_FILES) @@ -146,4 +148,5 @@ else() endif() cc_common_after_target(${target_name}) -endmacro() \ No newline at end of file +endmacro() + From a50a57ae1f7bfe4fb0ab2b1630ada93dc16ad0c5 Mon Sep 17 00:00:00 2001 From: Zeqiang Li Date: Thu, 25 Aug 2022 15:24:40 +0800 Subject: [PATCH 07/73] fix buffer gc wrong index on metal (#12507) * fix buffer gc wrong index on metal --- native/cocos/renderer/gfx-metal/MTLDevice.h | 2 +- native/cocos/renderer/gfx-metal/MTLDevice.mm | 22 ++++----- .../cocos/renderer/gfx-metal/MTLGPUObjects.h | 49 +++---------------- 3 files changed, 19 insertions(+), 54 deletions(-) diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index e67ff95104..cd1e82d15f 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -67,7 +67,7 @@ public: void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; - void onPresentCompleted(); + void onPresentCompleted(uint32_t index); inline void *getMTLCommandQueue() const { return _mtlCommandQueue; } inline void *getMTLDevice() const { return _mtlDevice; } diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 40131d8405..ba564eb738 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -75,7 +75,7 @@ CCMTLDevice::~CCMTLDevice() { bool CCMTLDevice::doInit(const DeviceInfo &info) { _gpuDeviceObj = ccnew CCMTLGPUDeviceObject; - _inFlightSemaphore = ccnew CCMTLSemaphore(MAX_FRAMES_IN_FLIGHT); + _inFlightSemaphore = ccnew CCMTLSemaphore(3); _currentFrameIndex = 0; id mtlDevice = MTLCreateSystemDefaultDevice(); @@ -164,14 +164,13 @@ void CCMTLDevice::doDestroy() { CC_SAFE_DESTROY_AND_DELETE(_cmdBuff); CCMTLGPUGarbageCollectionPool::getInstance()->flush(); - - if (_inFlightSemaphore) { - // has present ? syncSuccess : no need to wait; + + for(size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { _inFlightSemaphore->trySyncAll(1000); + CC_SAFE_DELETE(_inFlightSemaphore); + _inFlightSemaphore = nullptr; } - CC_SAFE_DELETE(_inFlightSemaphore); - for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { CC_SAFE_DELETE(_gpuStagingBufferPools[i]); _gpuStagingBufferPools[i] = nullptr; @@ -210,6 +209,7 @@ void CCMTLDevice::present() { _numTriangles = queue->gpuQueueObj()->numTriangles; //hold this pointer before update _currentFrameIndex + auto tempIndex = _currentFrameIndex; _currentBufferPoolId = _currentFrameIndex; _currentFrameIndex = (_currentFrameIndex + 1) % MAX_FRAMES_IN_FLIGHT; @@ -232,18 +232,18 @@ void CCMTLDevice::present() { [drawable release]; } [cmdBuffer addCompletedHandler:^(id commandBuffer) { - onPresentCompleted(); + onPresentCompleted(tempIndex); }]; [cmdBuffer commit]; } } -void CCMTLDevice::onPresentCompleted() { - if (_currentBufferPoolId >= 0 && _currentBufferPoolId < MAX_FRAMES_IN_FLIGHT) { - CCMTLGPUStagingBufferPool *bufferPool = _gpuStagingBufferPools[_currentBufferPoolId]; +void CCMTLDevice::onPresentCompleted(uint32_t index) { + if (index >= 0 && index < MAX_FRAMES_IN_FLIGHT) { + CCMTLGPUStagingBufferPool *bufferPool = _gpuStagingBufferPools[index]; if (bufferPool) { bufferPool->reset(); - CCMTLGPUGarbageCollectionPool::getInstance()->clear(_currentBufferPoolId); + CCMTLGPUGarbageCollectionPool::getInstance()->clear(index); } } _inFlightSemaphore->signal(); diff --git a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h index b478a7e4a4..9a8b048138 100644 --- a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h +++ b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h @@ -171,17 +171,10 @@ public: ~CCMTLGPUStagingBufferPool() { for (auto &buffer : _pool) { - if (_tripleEnabled) { - for (id mtlBuf : buffer.dynamicDataBuffers) { - [mtlBuf release]; - } - buffer.dynamicDataBuffers.clear(); - buffer.mtlBuffer = nil; - } else { - [buffer.mtlBuffer release]; - buffer.mtlBuffer = nil; - } + [buffer.mtlBuffer release]; + buffer.mtlBuffer = nil; } + _pool.clear(); } @@ -199,22 +192,12 @@ public: } } if (!buffer) { - uint32_t mbNeeds = mu::roundUp(gpuBuffer->size, MegaBytesToBytes); - mbNeeds = cc::utils::nextPOT(mbNeeds); - CC_ASSERT(mbNeeds > gpuBuffer->size / static_cast(MegaBytesToBytes)); + uint32_t needs = mu::alignUp(gpuBuffer->size, MegaBytesToBytes); _pool.resize(bufferCount + 1); buffer = &_pool.back(); - if (_tripleEnabled) { - for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { - // Create a new buffer with enough capacity to store one instance of the dynamic buffer data - id dataBuffer = [_device newBufferWithLength:mbNeeds * MegaBytesToBytes options:MTLResourceStorageModeShared]; - buffer->dynamicDataBuffers[i] = dataBuffer; - } - buffer->mtlBuffer = buffer->dynamicDataBuffers[0]; - } else { - buffer->mtlBuffer = [_device newBufferWithLength:mbNeeds * MegaBytesToBytes options:MTLResourceStorageModeShared]; - } + + buffer->mtlBuffer = [_device newBufferWithLength:needs options:MTLResourceStorageModeShared]; buffer->mappedData = (uint8_t *)buffer->mtlBuffer.contents; offset = 0; } @@ -222,22 +205,7 @@ public: gpuBuffer->startOffset = offset; gpuBuffer->mappedData = buffer->mappedData + offset; buffer->curOffset = offset + gpuBuffer->size; - } - - void updateInflightBuffer() { - if (_tripleEnabled) { - _inflightIndex = ((_inflightIndex + 1) % MAX_FRAMES_IN_FLIGHT); - - size_t bufferCount = _pool.size(); - Buffer *buffer = nullptr; - for (size_t idx = 0; idx < bufferCount; idx++) { - buffer = &_pool[idx]; - id prevFrameBuffer = buffer->mtlBuffer; - buffer->mtlBuffer = buffer->dynamicDataBuffers[_inflightIndex]; - memcpy((uint8_t *)buffer->mtlBuffer.contents, prevFrameBuffer.contents, buffer->curOffset); - buffer->mappedData = (uint8_t *)buffer->mtlBuffer.contents; - } - } + } void reset() { @@ -260,13 +228,10 @@ public: protected: struct Buffer { id mtlBuffer = nil; - ccstd::vector> dynamicDataBuffers{MAX_FRAMES_IN_FLIGHT}; uint8_t *mappedData = nullptr; uint32_t curOffset = 0; }; - bool _tripleEnabled = false; - uint32_t _inflightIndex = 0; id _device = nil; ccstd::vector _pool; }; From cf24d5aac515243039949c401df83b544eccefde Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Thu, 25 Aug 2022 18:08:25 +0800 Subject: [PATCH 08/73] fix potential null context (#12546) --- native/cocos/renderer/gfx-gles2/GLES2Device.cpp | 2 ++ native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp | 10 +++++++++- native/cocos/renderer/gfx-gles3/GLES3Device.cpp | 2 ++ native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp | 10 +++++++++- 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index ff2f3d6433..086d008d2f 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -235,6 +235,8 @@ void GLES2Device::doDestroy() { } void GLES2Device::acquire(Swapchain *const *swapchains, uint32_t count) { + _gpuContext->makeCurrent(); + if (_onAcquire) _onAcquire->execute(); _swapchains.clear(); diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp index 74d9cf86d9..93647db5fd 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp @@ -289,9 +289,17 @@ void GLES2GPUContext::bindContext(bool bound) { void GLES2GPUContext::makeCurrent(const GLES2GPUSwapchain *drawSwapchain, const GLES2GPUSwapchain *readSwapchain) { EGLSurface drawSurface = drawSwapchain ? drawSwapchain->eglSurface : _eglCurrentDrawSurface; EGLSurface readSurface = readSwapchain ? readSwapchain->eglSurface : _eglCurrentReadSurface; - if (_eglCurrentDrawSurface == drawSurface && _eglCurrentReadSurface == readSurface) return; + EGLContext prevContext = eglGetCurrentContext(); + + if (_eglCurrentDrawSurface == drawSurface && _eglCurrentReadSurface == readSurface && _eglCurrentContext == prevContext) { + return; + } makeCurrent(drawSurface, readSurface, _eglCurrentContext); + + if (prevContext != _eglCurrentContext) { + resetStates(); + } } void GLES2GPUContext::present(const GLES2GPUSwapchain *swapchain) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index db87a8db2b..be7b4f6015 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -251,6 +251,8 @@ void GLES3Device::doDestroy() { } void GLES3Device::acquire(Swapchain *const *swapchains, uint32_t count) { + _gpuContext->makeCurrent(); + if (_onAcquire) _onAcquire->execute(); _swapchains.clear(); diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp index 9350ba4557..cf5afee18c 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp @@ -297,9 +297,17 @@ void GLES3GPUContext::bindContext(bool bound) { void GLES3GPUContext::makeCurrent(const GLES3GPUSwapchain *drawSwapchain, const GLES3GPUSwapchain *readSwapchain) { EGLSurface drawSurface = drawSwapchain && drawSwapchain->eglSurface ? drawSwapchain->eglSurface : _eglCurrentDrawSurface; EGLSurface readSurface = readSwapchain && readSwapchain->eglSurface ? readSwapchain->eglSurface : _eglCurrentReadSurface; - if (_eglCurrentDrawSurface == drawSurface && _eglCurrentReadSurface == readSurface) return; + EGLContext prevContext = eglGetCurrentContext(); + + if (_eglCurrentDrawSurface == drawSurface && _eglCurrentReadSurface == readSurface && _eglCurrentContext == prevContext) { + return; + } makeCurrent(drawSurface, readSurface, _eglCurrentContext); + + if (prevContext != _eglCurrentContext) { + resetStates(); + } } void GLES3GPUContext::present(const GLES3GPUSwapchain *swapchain) { From 43f7aa0d35d207285a865d127583be3fe65cc918 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 26 Aug 2022 11:13:11 +0800 Subject: [PATCH 09/73] [v3.6.1] Optimize JSBClassType::findClass if sub class type is not found. (#12548) --- native/cocos/bindings/manual/jsb_classtype.cpp | 2 +- native/cocos/bindings/manual/jsb_classtype.h | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/native/cocos/bindings/manual/jsb_classtype.cpp b/native/cocos/bindings/manual/jsb_classtype.cpp index 34cd433a83..2517dbe8d9 100644 --- a/native/cocos/bindings/manual/jsb_classtype.cpp +++ b/native/cocos/bindings/manual/jsb_classtype.cpp @@ -25,4 +25,4 @@ #include "jsb_classtype.h" -ccstd::unordered_map JSBClassType::jsbClassTypeMap; +ccstd::unordered_map JSBClassType::jsbClassTypeMap; diff --git a/native/cocos/bindings/manual/jsb_classtype.h b/native/cocos/bindings/manual/jsb_classtype.h index 7a764f5c1e..388fc4dbd7 100644 --- a/native/cocos/bindings/manual/jsb_classtype.h +++ b/native/cocos/bindings/manual/jsb_classtype.h @@ -41,13 +41,14 @@ public: template static se::Class *findClass(const T *nativeObj) { bool found = false; - ccstd::string typeName = typeid(*nativeObj).name(); - auto iter = jsbClassTypeMap.find(typeName); + const char *typeNameFromValue = typeid(*nativeObj).name(); + auto iter = jsbClassTypeMap.find(typeNameFromValue); if (iter == jsbClassTypeMap.end()) { - typeName = typeid(T).name(); - iter = jsbClassTypeMap.find(typeName); + const char *typeNameFromType = typeid(T).name(); + iter = jsbClassTypeMap.find(typeNameFromType); if (iter != jsbClassTypeMap.end()) { found = true; + jsbClassTypeMap.emplace(typeNameFromValue, iter->second); } } else { found = true; @@ -60,5 +61,5 @@ public: } private: - static ccstd::unordered_map jsbClassTypeMap; + static ccstd::unordered_map jsbClassTypeMap; }; From a422233d3190704fd21c1a49a66ffaac2af23b23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Fri, 26 Aug 2022 14:56:13 +0800 Subject: [PATCH 10/73] fix find_pacakge options (#12550) --- native/cmake/scripts/plugins_parser.js | 12 ++++++------ templates/cmake/common.cmake | 10 +++++----- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/native/cmake/scripts/plugins_parser.js b/native/cmake/scripts/plugins_parser.js index 3e8502f66d..7106a835d5 100644 --- a/native/cmake/scripts/plugins_parser.js +++ b/native/cmake/scripts/plugins_parser.js @@ -191,10 +191,11 @@ console.log(`Engine version: ${read_engine_version()}`); /// Generate Pre-AutoLoadPlugins.cmake -let output_lines = ["# plugins found & enabled in search path", "", ""]; +let output_lines = ["# plugins found & enabled in search path", + "# To disable automatic update of this file, set SKIP_SCAN_PLUGINS to ON.", + ""]; for (let plugin_dir of cc_config_json_list) { let load_plugins = []; - let plugin_search_path = {}; try { let maybe_plugin_name = path.basename(plugin_dir); console.log(`Parsing plugin directory ${maybe_plugin_name}`); @@ -215,7 +216,6 @@ for (let plugin_dir of cc_config_json_list) { continue; } const packages = parse_package_dependency(cc_plugin_json); - const platform_plugin_dir = path.join(plugin_dir, PLATFORM_NAME_FROM_CMAKE); const cc_project_dir = path.dirname(plugin_cmake_output_file); let project_to_plugin_dir = path.relative(cc_project_dir, plugin_dir).replace(/\\/g, '/'); project_to_plugin_dir = `\${CC_PROJECT_DIR}/${project_to_plugin_dir}`; @@ -237,9 +237,9 @@ for (let plugin_dir of cc_config_json_list) { } else { output_lines.push(`find_package(${plg[0]}`); } + output_lines.push(` REQUIRED`); output_lines.push(` NAMES "${plg[0]}"`); - output_lines.push(` PATHS\n${plugin_root_path_for_platform.map(x => ' "' + x + '"').join("\n")}`); - output_lines.push(` NO_DEFAULT_PATH`); + output_lines.push(`# NO_DEFAULT_PATH`); output_lines.push(`)`); } if (packages.length > 0) { @@ -268,4 +268,4 @@ if (cc_config_json_list.length == 0) { fs.writeFileSync(plugin_cmake_output_file, output_lines.join("\n") + "\n", { encoding: 'utf8' }); } } -process.exit(0); \ No newline at end of file +process.exit(0); diff --git a/templates/cmake/common.cmake b/templates/cmake/common.cmake index a07ec4c37c..5d5e733f9c 100644 --- a/templates/cmake/common.cmake +++ b/templates/cmake/common.cmake @@ -77,11 +77,11 @@ function(cc_gen_plugin_cmake_hook) if("${NODE_EXECUTABLE}" STREQUAL "NODE_EXECUTABLE-NOTFOUND") message(STATUS "NodeJS is not found in $PATH, skip searching native plugins.") else() - message(STATUS " execute plugin_parser.js ${NODE_EXECUTABLE-NOTFOUND}") - execute_process(COMMAND ${NODE_EXECUTABLE} ${COCOS_X_PATH}/cmake/scripts/plugins_parser.js - ${plugin_args_info} - ${load_plugin_cmake} - ${PLATFORM_FOLDER} + message(STATUS " execute ${NODE_EXECUTABLE} plugin_parser.js") + execute_process(COMMAND ${NODE_EXECUTABLE} "${COCOS_X_PATH}/cmake/scripts/plugins_parser.js" + "${plugin_args_info}" + "${load_plugin_cmake}" + "${PLATFORM_FOLDER}" WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) endif() From f6e79631875361b9186bd329e2e6928ca62ba9cf Mon Sep 17 00:00:00 2001 From: zxx43 Date: Fri, 26 Aug 2022 16:06:08 +0800 Subject: [PATCH 11/73] modify gpu particle layout (#12443) --- cocos/particle/models/particle-batch-model.ts | 3 +-- .../renderer/particle-system-renderer-gpu.ts | 8 +++--- .../builtin/internal/particle-vs-gpu.chunk | 26 ++++++++++++------- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index a28eb9fd4c..cf56b143a8 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -491,6 +491,7 @@ export default class ParticleBatchModel extends scene.Model { this._vdataF32![idx++] = p.rotation.x; this._vdataF32![idx++] = p.rotation.y; this._vdataF32![idx++] = p.rotation.z; + this._vdataF32![idx++] = p.randomSeed; this._vdataF32![idx++] = p.startColor.r / 255.0; this._vdataF32![idx++] = p.startColor.g / 255.0; @@ -502,8 +503,6 @@ export default class ParticleBatchModel extends scene.Model { this._vdataF32![idx++] = p.velocity.z; this._vdataF32![idx++] = p.startLifetime; - this._vdataF32![idx++] = p.randomSeed; - offset += this._vertAttrsFloatCount; } diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index 9255b25cd8..3e7e27a7b9 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -76,7 +76,7 @@ const _vert_attr_name = { DIR_LIFE: 'a_dir_life', RANDOM_SEED: 'a_rndSeed', VERT_SIZE_FID: 'a_size_fid', - VERT_ROTATION: 'a_rotation', + VERT_ROTATION_RND: 'a_rotation_rnd', VERT_UV: 'a_uv', }; @@ -105,20 +105,18 @@ const _gpu_vert_attr_mesh = [ const _gpu_vert_attr_ins = [ new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_ROTATION_RND, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), new Attribute(_vert_attr_name.VERT_UV, Format.RGB32F, false, 1), ]; const _gpu_vert_attr_mesh_ins = [ new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_ROTATION_RND, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), // mesh uv new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F, false, 1), // mesh position new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, 1), // mesh normal diff --git a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk index bd886efdc5..d5712eae78 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk +++ b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk @@ -35,15 +35,15 @@ uniform TickConstants { in vec4 a_position_starttime; // center position,particle start time in vec4 a_color; in vec4 a_dir_life; // xyz:particle start velocity,w:particle lifetime -in float a_rndSeed; #if !CC_INSTANCE_PARTICLE in vec4 a_size_uv; // xyz:size, w:uv_0 in vec4 a_rotation_uv; // xyz:rotation, w:uv_1 + in float a_rndSeed; #endif #if CC_INSTANCE_PARTICLE - in vec4 a_size_fid; // xyz:size, w:fid - in vec3 a_rotation; // xyz:rotation + in vec4 a_size_fid; // xyz:size, w:fid + in vec4 a_rotation_rnd; // xyz:rotation, w:random in vec3 a_uv; #endif @@ -178,6 +178,12 @@ vec4 toQuat(vec3 rotation) { } vec4 gpvs_main () { + #if CC_INSTANCE_PARTICLE + float randSeed = a_rotation_rnd.w; + #else + float randSeed = a_rndSeed; + #endif + float activeTime = u_timeDelta.x - a_position_starttime.w; float normalizedTime = clamp(activeTime / a_dir_life.w, 0.0, 1.0); @@ -212,7 +218,7 @@ vec4 gpvs_main () { } else { vec3 size_0 = unpackCurveData(size_over_time_tex0, timeCoord0); vec3 size_1 = unpackCurveData(size_over_time_tex0, timeCoord1); - float factor_s = pseudoRandom(a_rndSeed + SIZE_OVERTIME_RAND_OFFSET); + float factor_s = pseudoRandom(randSeed + SIZE_OVERTIME_RAND_OFFSET); size *= mix(size_0, size_1, factor_s); } #endif @@ -227,7 +233,7 @@ vec4 gpvs_main () { } else { vec3 force_0 = unpackCurveData(force_over_time_tex0, timeCoord0); vec3 force_1 = unpackCurveData(force_over_time_tex0, timeCoord1); - float factor_f = pseudoRandom(a_rndSeed + FORCE_OVERTIME_RAND_OFFSET); + float factor_f = pseudoRandom(randSeed + FORCE_OVERTIME_RAND_OFFSET); forceAnim = mix(force_0, force_1, factor_f); } vec4 forceTrack = vec4(forceAnim, 0.); @@ -247,7 +253,7 @@ vec4 gpvs_main () { } else { vec3 vectory_0 = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0); vec3 vectory_1 = unpackCurveData(velocity_over_time_tex0, timeCoord1, speedModifier1); - float factor_v = pseudoRandom(a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET); + float factor_v = pseudoRandom(randSeed + VELOCITY_OVERTIME_RAND_OFFSET); velocityAnim = mix(vectory_0, vectory_1, factor_v); speedModifier0 = mix(speedModifier0, speedModifier1, factor_v); } @@ -273,7 +279,7 @@ vec4 gpvs_main () { vec3 startRotation = a_rotation_uv.xyz; #endif #if CC_INSTANCE_PARTICLE - vec3 startRotation = a_rotation; + vec3 startRotation = a_rotation_rnd.xyz; #endif #if CC_RENDER_MODE != RENDER_MODE_MESH #if CC_RENDER_MODE == RENDER_MODE_BILLBOARD @@ -300,7 +306,7 @@ vec4 gpvs_main () { } else { vec3 rotation_0 = unpackCurveData(rotation_over_time_tex0, timeCoord0); vec3 rotation_1 = unpackCurveData(rotation_over_time_tex0, timeCoord1); - float factor_r = pseudoRandom(a_rndSeed + ROTATION_OVERTIME_RAND_OFFSET); + float factor_r = pseudoRandom(randSeed + ROTATION_OVERTIME_RAND_OFFSET); vec3 euler = mix(rotation_0, rotation_1, factor_r) * normalizedTime * a_dir_life.w; #if CC_RENDER_MODE == RENDER_MODE_VERTICAL_BILLBOARD || CC_RENDER_MODE == RENDER_MODE_HORIZONTAL_BILLBOARD euler = vec3(0.0, 0.0, euler.z); @@ -319,7 +325,7 @@ vec4 gpvs_main () { } else { vec4 color_0 = texture(color_over_time_tex0, timeCoord0); vec4 color_1 = texture(color_over_time_tex0, timeCoord1); - float factor_c = pseudoRandom(a_rndSeed + COLOR_OVERTIME_RAND_OFFSET); + float factor_c = pseudoRandom(randSeed + COLOR_OVERTIME_RAND_OFFSET); color = a_color * mix(color_0, color_1, factor_c); } #endif @@ -376,7 +382,7 @@ vec4 gpvs_main () { } else { vec3 frameInfo0 = unpackCurveData(texture_animation_tex0, timeCoord0); vec3 frameInfo1 = unpackCurveData(texture_animation_tex0, timeCoord1); - float factor_t = pseudoRandom(a_rndSeed + TEXTURE_ANIMATION_RAND_OFFSET); + float factor_t = pseudoRandom(randSeed + TEXTURE_ANIMATION_RAND_OFFSET); frameInfo = mix(frameInfo0, frameInfo1, factor_t); } startFrame = frameInfo.x / u_anim_info.y; From e7a0a780174aa554ea685038e60605d20ba5aef8 Mon Sep 17 00:00:00 2001 From: jk20012001 Date: Fri, 26 Aug 2022 17:45:59 +0800 Subject: [PATCH 12/73] move LDR fog after tone mapping for smooth fading with solid clear color (#12571) --- editor/assets/chunks/legacy/standard-surface-entry.chunk | 4 ++-- .../render-to-scene/pipeline/forward-fs.chunk | 7 +++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/editor/assets/chunks/legacy/standard-surface-entry.chunk b/editor/assets/chunks/legacy/standard-surface-entry.chunk index 5abc13073b..78f968872d 100644 --- a/editor/assets/chunks/legacy/standard-surface-entry.chunk +++ b/editor/assets/chunks/legacy/standard-surface-entry.chunk @@ -31,11 +31,11 @@ \ void main () { \ StandardSurface s; surf(s); \ - vec4 color = CCStandardShadingBase(s, CC_SHADOW_POSITION); \ + vec4 color = CCFragOutput(CCStandardShadingBase(s, CC_SHADOW_POSITION)); \ #if CC_USE_FOG != CC_FOG_NONE \ CC_APPLY_FOG(color, s.position.xyz); \ #endif \ - fragColorX = CCFragOutput(color); \ + fragColorX = color; \ } \ \ #elif CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED \ diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index 3b173b5636..60ad5b178c 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -104,10 +104,6 @@ void main() { // Shading vec4 color = CCSurfacesShading(surfaceData, lightingResult); - #if !CC_FORWARD_ADD && CC_USE_FOG != CC_FOG_NONE - CC_APPLY_FOG_BASE(color, fogFactor); - #endif - #if CC_USE_DEBUG_VIEW && CC_SURFACES_ENABLE_DEBUG_VIEW // CSM Debug if (IS_DEBUG_VIEW_MISC_ENABLE_CSM_LAYER_COLORATION) { @@ -132,6 +128,9 @@ void main() { #endif color.rgb = LinearToSRGB(color.rgb); + #if !CC_FORWARD_ADD && CC_USE_FOG != CC_FOG_NONE + CC_APPLY_FOG_BASE(color, fogFactor); + #endif fragColorX = CCSurfacesDebugDisplayInvalidNumber(color); } From bc5c3a1d608d24891dfcce5f7b8c3456ccb47005 Mon Sep 17 00:00:00 2001 From: timlyeee <43355299+timlyeee@users.noreply.github.com> Date: Mon, 29 Aug 2022 13:49:23 +0800 Subject: [PATCH 13/73] Support wav audio play on Windows (#12422) --- .github/workflows/native-linter-android.yml | 3 + native/CMakeLists.txt | 228 +++++++-------- .../cocos/audio/android/AudioDecoderWav.cpp | 6 +- native/cocos/audio/android/AudioMixer.cpp | 272 +++++++++--------- native/cocos/audio/android/AudioResampler.cpp | 2 +- native/cocos/audio/android/IVolumeProvider.h | 2 +- .../decoder}/AudioDecoder.cpp | 11 +- .../decoder}/AudioDecoder.h | 3 +- .../decoder}/AudioDecoderManager.cpp | 15 +- .../decoder}/AudioDecoderManager.h | 0 .../decoder}/AudioDecoderMp3.cpp | 6 +- .../decoder}/AudioDecoderMp3.h | 2 +- .../decoder}/AudioDecoderOgg.cpp | 7 +- .../decoder}/AudioDecoderOgg.h | 2 +- .../audio/common/decoder/AudioDecoderWav.cpp | 96 +++++++ .../audio/common/decoder/AudioDecoderWav.h | 77 +++++ .../format.c => common/utils/format.cpp} | 4 +- .../utils/include}/format.h | 3 +- .../utils/include}/minifloat.h | 14 +- .../utils/include}/primitives.h | 41 +-- .../utils/include}/tinysndfile.h | 22 +- .../utils}/minifloat.cpp | 6 +- .../utils/primitives.cpp} | 184 ++++++------ .../utils}/private/private.h | 19 +- .../{android => common/utils}/tinysndfile.cpp | 21 +- .../audio/{oalsoft => include}/AudioMacros.h | 2 +- native/cocos/audio/oalsoft/AudioCache.cpp | 4 +- native/cocos/audio/oalsoft/AudioCache.h | 2 +- .../cocos/audio/oalsoft/AudioEngine-soft.cpp | 4 +- native/cocos/audio/oalsoft/AudioPlayer.cpp | 4 +- native/cocos/audio/ohos/AudioDecoderWav.h | 2 +- 31 files changed, 628 insertions(+), 436 deletions(-) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoder.cpp (94%) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoder.h (99%) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoderManager.cpp (87%) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoderManager.h (100%) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoderMp3.cpp (98%) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoderMp3.h (98%) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoderOgg.cpp (97%) rename native/cocos/audio/{oalsoft => common/decoder}/AudioDecoderOgg.h (98%) create mode 100644 native/cocos/audio/common/decoder/AudioDecoderWav.cpp create mode 100644 native/cocos/audio/common/decoder/AudioDecoderWav.h rename native/cocos/audio/{android/audio_utils/format.c => common/utils/format.cpp} (97%) rename native/cocos/audio/{android/audio_utils/include/audio_utils => common/utils/include}/format.h (99%) rename native/cocos/audio/{android/audio_utils/include/audio_utils => common/utils/include}/minifloat.h (91%) rename native/cocos/audio/{android/audio_utils/include/audio_utils => common/utils/include}/primitives.h (98%) rename native/cocos/audio/{android => common/utils/include}/tinysndfile.h (81%) rename native/cocos/audio/{android/audio_utils => common/utils}/minifloat.cpp (94%) rename native/cocos/audio/{android/audio_utils/primitives.c => common/utils/primitives.cpp} (70%) rename native/cocos/audio/{android/audio_utils => common/utils}/private/private.h (80%) rename native/cocos/audio/{android => common/utils}/tinysndfile.cpp (97%) rename native/cocos/audio/{oalsoft => include}/AudioMacros.h (99%) diff --git a/.github/workflows/native-linter-android.yml b/.github/workflows/native-linter-android.yml index 3a1b8e2709..d2af9afe70 100644 --- a/.github/workflows/native-linter-android.yml +++ b/.github/workflows/native-linter-android.yml @@ -77,6 +77,9 @@ jobs: - exclude: 'native/cocos/bindings/manual/jsb_conversions.*' - exclude: 'native/cocos/bindings/jswrapper/v8/debugger/**' - exclude: 'native/cocos/audio/android/audio_utils/**' + - exclude: 'native/cocos/audio/android/AudioMixer.cpp' + - exclude: 'native/cocos/audio/android/AudioResampler.cpp' + - exclude: 'native/cocos/audio/common/utils/**' allChanges: - added|modified|deleted: '**' skipedDebug: diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index af31c85f63..95d2c31c0e 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -219,153 +219,157 @@ include(${EXTERNAL_ROOT}/CMakeLists.txt) ##### audio if(USE_AUDIO) cocos_source_files( - cocos/audio/AudioEngine.cpp - cocos/audio/include/AudioEngine.h - cocos/audio/include/AudioDef.h - cocos/audio/include/Export.h + cocos/audio/AudioEngine.cpp + cocos/audio/include/AudioEngine.h + cocos/audio/include/AudioDef.h + cocos/audio/include/Export.h ) if(WINDOWS) cocos_source_files( + cocos/audio/common/utils/tinysndfile.cpp +NO_WERROR cocos/audio/common/utils/primitives.cpp + cocos/audio/common/utils/include/tinysndfile.h + cocos/audio/common/utils/include/primitives.h + cocos/audio/common/utils/private/private.h + cocos/audio/common/decoder/AudioDecoder.cpp + cocos/audio/common/decoder/AudioDecoder.h + cocos/audio/common/decoder/AudioDecoderManager.cpp + cocos/audio/common/decoder/AudioDecoderManager.h + cocos/audio/common/decoder/AudioDecoderMp3.cpp + cocos/audio/common/decoder/AudioDecoderMp3.h + cocos/audio/common/decoder/AudioDecoderOgg.cpp + cocos/audio/common/decoder/AudioDecoderOgg.h + cocos/audio/common/decoder/AudioDecoderWav.cpp + cocos/audio/common/decoder/AudioDecoderWav.h cocos/audio/oalsoft/AudioCache.cpp cocos/audio/oalsoft/AudioCache.h - cocos/audio/oalsoft/AudioDecoder.cpp - cocos/audio/oalsoft/AudioDecoder.h - cocos/audio/oalsoft/AudioDecoderManager.cpp - cocos/audio/oalsoft/AudioDecoderManager.h - cocos/audio/oalsoft/AudioDecoderMp3.cpp - cocos/audio/oalsoft/AudioDecoderMp3.h - cocos/audio/oalsoft/AudioDecoderOgg.cpp - cocos/audio/oalsoft/AudioDecoderOgg.h cocos/audio/oalsoft/AudioEngine-soft.cpp cocos/audio/oalsoft/AudioEngine-soft.h - cocos/audio/oalsoft/AudioMacros.h + cocos/audio/include/AudioMacros.h cocos/audio/oalsoft/AudioPlayer.cpp cocos/audio/oalsoft/AudioPlayer.h ) elseif(LINUX OR QNX) cocos_source_files( + cocos/audio/common/decoder/AudioDecoder.cpp + cocos/audio/common/decoder/AudioDecoder.h + cocos/audio/common/decoder/AudioDecoderManager.cpp + cocos/audio/common/decoder/AudioDecoderManager.h + cocos/audio/common/decoder/AudioDecoderMp3.cpp + cocos/audio/common/decoder/AudioDecoderMp3.h + cocos/audio/common/decoder/AudioDecoderOgg.cpp + cocos/audio/common/decoder/AudioDecoderOgg.h cocos/audio/oalsoft/AudioCache.cpp cocos/audio/oalsoft/AudioCache.h - cocos/audio/oalsoft/AudioDecoder.cpp - cocos/audio/oalsoft/AudioDecoder.h - cocos/audio/oalsoft/AudioDecoderManager.cpp - cocos/audio/oalsoft/AudioDecoderManager.h - cocos/audio/oalsoft/AudioDecoderMp3.cpp - cocos/audio/oalsoft/AudioDecoderMp3.h - cocos/audio/oalsoft/AudioDecoderOgg.cpp - cocos/audio/oalsoft/AudioDecoderOgg.h cocos/audio/oalsoft/AudioEngine-soft.cpp cocos/audio/oalsoft/AudioEngine-soft.h - cocos/audio/oalsoft/AudioMacros.h + cocos/audio/include/AudioMacros.h cocos/audio/oalsoft/AudioPlayer.cpp cocos/audio/oalsoft/AudioPlayer.h ) elseif(ANDROID) cocos_source_files( - cocos/audio/android/AssetFd.cpp - cocos/audio/android/AssetFd.h - cocos/audio/android/audio.h - cocos/audio/android/AudioBufferProvider.h - cocos/audio/android/AudioDecoder.cpp - cocos/audio/android/AudioDecoder.h - cocos/audio/android/AudioDecoderMp3.cpp - cocos/audio/android/AudioDecoderMp3.h - cocos/audio/android/AudioDecoderOgg.cpp - cocos/audio/android/AudioDecoderOgg.h - cocos/audio/android/AudioDecoderProvider.cpp - cocos/audio/android/AudioDecoderProvider.h - cocos/audio/android/AudioDecoderSLES.cpp - cocos/audio/android/AudioDecoderSLES.h - cocos/audio/android/AudioDecoderWav.cpp - cocos/audio/android/AudioDecoderWav.h - cocos/audio/android/AudioEngine-inl.cpp - cocos/audio/android/AudioEngine-inl.h - cocos/audio/android/AudioMixer.cpp - cocos/audio/android/AudioMixer.h - cocos/audio/android/AudioMixerController.cpp - cocos/audio/android/AudioMixerController.h - cocos/audio/android/AudioMixerOps.h - cocos/audio/android/AudioPlayerProvider.cpp - cocos/audio/android/AudioPlayerProvider.h - cocos/audio/android/AudioResampler.cpp - cocos/audio/android/AudioResampler.h - cocos/audio/android/AudioResamplerCubic.cpp - cocos/audio/android/AudioResamplerCubic.h - cocos/audio/android/AudioResamplerPublic.h - cocos/audio/android/audio_utils/format.c - cocos/audio/android/audio_utils/include/audio_utils/format.h - cocos/audio/android/audio_utils/include/audio_utils/minifloat.h - cocos/audio/android/audio_utils/include/audio_utils/primitives.h - cocos/audio/android/audio_utils/minifloat.cpp - cocos/audio/android/audio_utils/primitives.c - cocos/audio/android/audio_utils/private/private.h - cocos/audio/android/cutils/bitops.h - cocos/audio/android/cutils/log.h - cocos/audio/android/IAudioPlayer.h - cocos/audio/android/ICallerThreadUtils.h - cocos/audio/android/IVolumeProvider.h - cocos/audio/android/mp3reader.cpp - cocos/audio/android/mp3reader.h - cocos/audio/android/OpenSLHelper.h - cocos/audio/android/PcmAudioPlayer.cpp - cocos/audio/android/PcmAudioPlayer.h - cocos/audio/android/PcmAudioService.cpp - cocos/audio/android/PcmAudioService.h - cocos/audio/android/PcmBufferProvider.cpp - cocos/audio/android/PcmBufferProvider.h - cocos/audio/android/PcmData.cpp - cocos/audio/android/PcmData.h - cocos/audio/android/tinysndfile.cpp - cocos/audio/android/tinysndfile.h - cocos/audio/android/Track.cpp - cocos/audio/android/Track.h - cocos/audio/android/UrlAudioPlayer.cpp - cocos/audio/android/UrlAudioPlayer.h - cocos/audio/android/utils/Compat.h - cocos/audio/android/utils/Errors.h - cocos/audio/android/utils/Utils.cpp - cocos/audio/android/utils/Utils.h + cocos/audio/common/utils/include/primitives.h + cocos/audio/common/utils/include/format.h + cocos/audio/common/utils/include/minifloat.h + cocos/audio/common/utils/include/tinysndfile.h + cocos/audio/common/utils/private/private.h + cocos/audio/common/utils/minifloat.cpp + cocos/audio/common/utils/primitives.cpp + cocos/audio/common/utils/tinysndfile.cpp + cocos/audio/common/utils/format.cpp + cocos/audio/android/AssetFd.cpp + cocos/audio/android/AssetFd.h + cocos/audio/android/audio.h + cocos/audio/android/AudioBufferProvider.h + cocos/audio/android/AudioDecoder.cpp + cocos/audio/android/AudioDecoder.h + cocos/audio/android/AudioDecoderMp3.cpp + cocos/audio/android/AudioDecoderMp3.h + cocos/audio/android/AudioDecoderOgg.cpp + cocos/audio/android/AudioDecoderOgg.h + cocos/audio/android/AudioDecoderProvider.cpp + cocos/audio/android/AudioDecoderProvider.h + cocos/audio/android/AudioDecoderSLES.cpp + cocos/audio/android/AudioDecoderSLES.h + cocos/audio/android/AudioDecoderWav.cpp + cocos/audio/android/AudioDecoderWav.h + cocos/audio/android/AudioEngine-inl.cpp + cocos/audio/android/AudioEngine-inl.h + cocos/audio/android/AudioMixer.cpp + cocos/audio/android/AudioMixer.h + cocos/audio/android/AudioMixerController.cpp + cocos/audio/android/AudioMixerController.h + cocos/audio/android/AudioMixerOps.h + cocos/audio/android/AudioPlayerProvider.cpp + cocos/audio/android/AudioPlayerProvider.h + cocos/audio/android/AudioResampler.cpp + cocos/audio/android/AudioResampler.h + cocos/audio/android/AudioResamplerCubic.cpp + cocos/audio/android/AudioResamplerCubic.h + cocos/audio/android/AudioResamplerPublic.h + cocos/audio/android/cutils/bitops.h + cocos/audio/android/cutils/log.h + cocos/audio/android/IAudioPlayer.h + cocos/audio/android/ICallerThreadUtils.h + cocos/audio/android/IVolumeProvider.h + cocos/audio/android/mp3reader.cpp + cocos/audio/android/mp3reader.h + cocos/audio/android/OpenSLHelper.h + cocos/audio/android/PcmAudioPlayer.cpp + cocos/audio/android/PcmAudioPlayer.h + cocos/audio/android/PcmAudioService.cpp + cocos/audio/android/PcmAudioService.h + cocos/audio/android/PcmBufferProvider.cpp + cocos/audio/android/PcmBufferProvider.h + cocos/audio/android/PcmData.cpp + cocos/audio/android/PcmData.h + cocos/audio/android/Track.cpp + cocos/audio/android/Track.h + cocos/audio/android/UrlAudioPlayer.cpp + cocos/audio/android/UrlAudioPlayer.h + cocos/audio/android/utils/Compat.h + cocos/audio/android/utils/Errors.h + cocos/audio/android/utils/Utils.cpp + cocos/audio/android/utils/Utils.h ) elseif(OHOS) cocos_source_files( + cocos/audio/common/utils/tinysndfile.cpp + cocos/audio/common/utils/primitives.cpp + cocos/audio/common/utils/include/tinysndfile.h + cocos/audio/common/utils/include/primitives.h + cocos/audio/common/decoder/AudioDecoder.cpp + cocos/audio/common/decoder/AudioDecoder.h + cocos/audio/common/decoder/AudioDecoderManager.cpp + cocos/audio/common/decoder/AudioDecoderManager.h + cocos/audio/common/decoder/AudioDecoderMp3.cpp + cocos/audio/common/decoder/AudioDecoderMp3.h + cocos/audio/common/decoder/AudioDecoderOgg.cpp + cocos/audio/common/decoder/AudioDecoderOgg.h + cocos/audio/common/decoder/AudioDecoderWav.cpp + cocos/audio/common/decoder/AudioDecoderWav.h cocos/audio/oalsoft/AudioCache.cpp cocos/audio/oalsoft/AudioCache.h - cocos/audio/oalsoft/AudioDecoderManager.cpp - cocos/audio/oalsoft/AudioDecoderManager.h - cocos/audio/oalsoft/AudioDecoder.cpp - cocos/audio/oalsoft/AudioDecoder.h - cocos/audio/oalsoft/AudioDecoderMp3.cpp - cocos/audio/oalsoft/AudioDecoderMp3.h - cocos/audio/oalsoft/AudioDecoderOgg.cpp - cocos/audio/oalsoft/AudioDecoderOgg.h cocos/audio/oalsoft/AudioEngine-soft.cpp cocos/audio/oalsoft/AudioEngine-soft.h - cocos/audio/oalsoft/AudioMacros.h + cocos/audio/include/AudioMacros.h cocos/audio/oalsoft/AudioPlayer.cpp cocos/audio/oalsoft/AudioPlayer.h - - cocos/audio/ohos/AudioDecoderWav.h - cocos/audio/ohos/AudioDecoderWav.cpp - # cocos/audio/ohos/AudioDecoderMp3.h - # cocos/audio/ohos/AudioDecoderMp3.cpp cocos/audio/ohos/FsCallback.h cocos/audio/ohos/FsCallback.cpp - - cocos/audio/android/tinysndfile.cpp - cocos/audio/android/tinysndfile.h - cocos/audio/android/audio_utils/primitives.c ) elseif(APPLE) cocos_source_files( - cocos/audio/apple/AudioDecoder.h - NO_WERROR NO_UBUILD cocos/audio/apple/AudioPlayer.mm - NO_WERROR NO_UBUILD cocos/audio/apple/AudioDecoder.mm - cocos/audio/apple/AudioPlayer.h - NO_WERROR NO_UBUILD cocos/audio/apple/AudioEngine-inl.mm - cocos/audio/apple/AudioMacros.h - NO_WERROR NO_UBUILD cocos/audio/apple/AudioCache.mm - cocos/audio/apple/AudioCache.h - cocos/audio/apple/AudioEngine-inl.h + cocos/audio/apple/AudioDecoder.h + NO_WERROR NO_UBUILD cocos/audio/apple/AudioPlayer.mm + NO_WERROR NO_UBUILD cocos/audio/apple/AudioDecoder.mm + cocos/audio/apple/AudioPlayer.h + NO_WERROR NO_UBUILD cocos/audio/apple/AudioEngine-inl.mm + cocos/audio/apple/AudioMacros.h + NO_WERROR NO_UBUILD cocos/audio/apple/AudioCache.mm + cocos/audio/apple/AudioCache.h + cocos/audio/apple/AudioEngine-inl.h ) endif() diff --git a/native/cocos/audio/android/AudioDecoderWav.cpp b/native/cocos/audio/android/AudioDecoderWav.cpp index fc76af5b8f..d3f384e447 100644 --- a/native/cocos/audio/android/AudioDecoderWav.cpp +++ b/native/cocos/audio/android/AudioDecoderWav.cpp @@ -26,11 +26,11 @@ THE SOFTWARE. #define LOG_TAG "AudioDecoderWav" #include "audio/android/AudioDecoderWav.h" -#include "audio/android/tinysndfile.h" +#include "audio/common/utils/include/tinysndfile.h" #include "platform/FileUtils.h" namespace cc { - +using namespace sf; //NOLINT AudioDecoderWav::AudioDecoderWav() { ALOGV("Create AudioDecoderWav"); } @@ -103,4 +103,4 @@ bool AudioDecoderWav::decodeToPcm() { return ret; } -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/audio/android/AudioMixer.cpp b/native/cocos/audio/android/AudioMixer.cpp index c93fdb0ccb..4486e0fc7d 100644 --- a/native/cocos/audio/android/AudioMixer.cpp +++ b/native/cocos/audio/android/AudioMixer.cpp @@ -26,7 +26,7 @@ #include #include "audio/android/audio.h" -#include "audio/android/audio_utils/include/audio_utils/primitives.h" +#include "audio/common/utils/include/primitives.h" #include "audio/android/AudioMixerOps.h" #include "audio/android/AudioMixer.h" #include "base/memory/Memory.h" @@ -66,15 +66,15 @@ static inline T max(const T &x, const T &y) { // Set kUseNewMixer to true to use the new mixer engine always. Otherwise the // original code will be used for stereo sinks, the new mixer for multichannel. -static const bool kUseNewMixer = false; +static const bool kUseNewMixer = false; //NOLINT // Set kUseFloat to true to allow floating input into the mixer engine. // If kUseNewMixer is false, this is ignored or may be overridden internally // because of downmix/upmix support. -static const bool kUseFloat = false; +static const bool kUseFloat = false; //NOLINT // Set to default copy buffer size in frames for input processing. -static const size_t kCopyBufferFrameCount = 256; +static const size_t kCopyBufferFrameCount = 256; //NOLINT namespace cc { @@ -105,8 +105,8 @@ AudioMixer::AudioMixer(size_t frameCount, uint32_t sampleRate, uint32_t maxNumTr mState.needsChanged = 0; mState.frameCount = frameCount; mState.hook = process__nop; - mState.outputTemp = NULL; - mState.resampleTemp = NULL; + mState.outputTemp = nullptr; + mState.resampleTemp = nullptr; //cjh mState.mLog = &mDummyLog; // mState.reserved @@ -115,10 +115,10 @@ AudioMixer::AudioMixer(size_t frameCount, uint32_t sampleRate, uint32_t maxNumTr // and mTrackNames is initially 0. However, leave it here until that's verified. track_t *t = mState.tracks; for (unsigned i = 0; i < MAX_NUM_TRACKS; i++) { - t->resampler = NULL; - //cjh t->downmixerBufferProvider = NULL; - // t->mReformatBufferProvider = NULL; - // t->mTimestretchBufferProvider = NULL; + t->resampler = nullptr; + //cjh t->downmixerBufferProvider = nullptr; + // t->mReformatBufferProvider = nullptr; + // t->mTimestretchBufferProvider = nullptr; t++; } } @@ -192,22 +192,22 @@ int AudioMixer::getTrackName(audio_channel_mask_t channelMask, t->channelMask = channelMask; t->sessionId = sessionId; // setBufferProvider(name, AudioBufferProvider *) is required before enable(name) - t->bufferProvider = NULL; - t->buffer.raw = NULL; + t->bufferProvider = nullptr; + t->buffer.raw = nullptr; // no initialization needed // t->buffer.frameCount - t->hook = NULL; - t->in = NULL; - t->resampler = NULL; + t->hook = nullptr; + t->in = nullptr; + t->resampler = nullptr; t->sampleRate = mSampleRate; // setParameter(name, TRACK, MAIN_BUFFER, mixBuffer) is required before enable(name) - t->mainBuffer = NULL; - t->auxBuffer = NULL; - t->mInputBufferProvider = NULL; - //cjh t->mReformatBufferProvider = NULL; - // t->downmixerBufferProvider = NULL; - // t->mPostDownmixReformatBufferProvider = NULL; - // t->mTimestretchBufferProvider = NULL; + t->mainBuffer = nullptr; + t->auxBuffer = nullptr; + t->mInputBufferProvider = nullptr; + //cjh t->mReformatBufferProvider = nullptr; + // t->downmixerBufferProvider = nullptr; + // t->mPostDownmixReformatBufferProvider = nullptr; + // t->mTimestretchBufferProvider = nullptr; t->mMixerFormat = AUDIO_FORMAT_PCM_16_BIT; t->mFormat = format; t->mMixerInFormat = selectMixerInFormat(format); @@ -279,7 +279,7 @@ bool AudioMixer::setChannelMasks(int name, // resampler channels may have changed. const uint32_t resetToSampleRate = track.sampleRate; delete track.resampler; - track.resampler = NULL; + track.resampler = nullptr; track.sampleRate = mSampleRate; // without resampler, track rate is device sample rate. // recreate the resampler with updated format, channels, saved sampleRate. track.setResampler(resetToSampleRate /*trackSampleRate*/, mSampleRate /*devSampleRate*/); @@ -291,11 +291,11 @@ void AudioMixer::track_t::unprepareForDownmix() { ALOGV("AudioMixer::unprepareForDownmix(%p)", this); mDownmixRequiresFormat = AUDIO_FORMAT_INVALID; - //cjh if (downmixerBufferProvider != NULL) { + //cjh if (downmixerBufferProvider != nullptr) { // // this track had previously been configured with a downmixer, delete it // ALOGV(" deleting old downmixer"); // delete downmixerBufferProvider; - // downmixerBufferProvider = NULL; + // downmixerBufferProvider = nullptr; // reconfigureBufferProviders(); // } else { @@ -344,14 +344,14 @@ status_t AudioMixer::track_t::prepareForDownmix() { void AudioMixer::track_t::unprepareForReformat() { ALOGV("AudioMixer::unprepareForReformat(%p)", this); bool requiresReconfigure = false; - //cjh if (mReformatBufferProvider != NULL) { + //cjh if (mReformatBufferProvider != nullptr) { // delete mReformatBufferProvider; - // mReformatBufferProvider = NULL; + // mReformatBufferProvider = nullptr; // requiresReconfigure = true; // } - // if (mPostDownmixReformatBufferProvider != NULL) { + // if (mPostDownmixReformatBufferProvider != nullptr) { // delete mPostDownmixReformatBufferProvider; - // mPostDownmixReformatBufferProvider = NULL; + // mPostDownmixReformatBufferProvider = nullptr; // requiresReconfigure = true; // } if (requiresReconfigure) { @@ -423,14 +423,14 @@ void AudioMixer::deleteTrackName(int name) { } // delete the resampler delete track.resampler; - track.resampler = NULL; + track.resampler = nullptr; // delete the downmixer mState.tracks[name].unprepareForDownmix(); // delete the reformatter mState.tracks[name].unprepareForReformat(); // delete the timestretch provider //cjh delete track.mTimestretchBufferProvider; - // track.mTimestretchBufferProvider = NULL; + // track.mTimestretchBufferProvider = nullptr; mTrackNames &= ~(1 << name); } @@ -554,7 +554,7 @@ static inline bool setVolumeRampVariables(float newVolume, int32_t ramp, // audio artifacts, so it never reaches the range limit of U4.28. // We safely use signed 16 and 32 bit integers here. const float scaledVolume = newVolume * AudioMixer::UNITY_GAIN_INT; // not neg, subnormal, nan - const int32_t intVolume = (scaledVolume >= (float)AudioMixer::UNITY_GAIN_INT) ? AudioMixer::UNITY_GAIN_INT : (int32_t)scaledVolume; + const int32_t intVolume = (scaledVolume >= static_cast(AudioMixer::UNITY_GAIN_INT)) ? AudioMixer::UNITY_GAIN_INT : static_cast(scaledVolume); // set integer volume ramp if (ramp != 0) { @@ -592,13 +592,13 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { track_t &track = mState.tracks[name]; int valueInt = static_cast(reinterpret_cast(value)); - int32_t *valueBuf = reinterpret_cast(value); + auto *valueBuf = reinterpret_cast(value); switch (target) { case TRACK: switch (param) { case CHANNEL_MASK: { - const audio_channel_mask_t trackChannelMask = + const auto trackChannelMask = static_cast(valueInt); if (setChannelMasks(name, trackChannelMask, track.mMixerChannelMask)) { ALOGV("setParameter(TRACK, CHANNEL_MASK, %x)", trackChannelMask); @@ -620,7 +620,7 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { } break; case FORMAT: { - audio_format_t format = static_cast(valueInt); + auto format = static_cast(valueInt); if (track.mFormat != format) { ALOG_ASSERT(audio_is_linear_pcm(format), "Invalid format %#x", format); track.mFormat = format; @@ -634,14 +634,14 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { /* case DOWNMIX_TYPE: break */ case MIXER_FORMAT: { - audio_format_t format = static_cast(valueInt); + auto format = static_cast(valueInt); if (track.mMixerFormat != format) { track.mMixerFormat = format; ALOGV("setParameter(TRACK, MIXER_FORMAT, %#x)", format); } } break; case MIXER_CHANNEL_MASK: { - const audio_channel_mask_t mixerChannelMask = + const auto mixerChannelMask = static_cast(valueInt); if (setChannelMasks(name, track.channelMask, mixerChannelMask)) { ALOGV("setParameter(TRACK, MIXER_CHANNEL_MASK, %#x)", mixerChannelMask); @@ -657,7 +657,7 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { switch (param) { case SAMPLE_RATE: ALOG_ASSERT(valueInt > 0, "bad sample rate %d", valueInt); - if (track.setResampler(uint32_t(valueInt), mSampleRate)) { + if (track.setResampler(static_cast(valueInt), mSampleRate)) { ALOGV("setParameter(RESAMPLE, SAMPLE_RATE, %u)", uint32_t(valueInt)); invalidateState(1 << name); @@ -669,7 +669,7 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { break; case REMOVE: delete track.resampler; - track.resampler = NULL; + track.resampler = nullptr; track.sampleRate = mSampleRate; invalidateState(1 << name); break; @@ -692,7 +692,7 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { } break; default: - if ((unsigned)param >= VOLUME0 && (unsigned)param < VOLUME0 + MAX_NUM_VOLUMES) { + if (static_cast(param) >= VOLUME0 && static_cast(param) < VOLUME0 + MAX_NUM_VOLUMES) { if (setVolumeRampVariables(*reinterpret_cast(value), target == RAMP_VOLUME ? mState.frameCount : 0, &track.volume[param - VOLUME0], &track.prevVolume[param - VOLUME0], @@ -739,10 +739,10 @@ void AudioMixer::setParameter(int name, int target, int param, void *value) { } bool AudioMixer::track_t::setResampler(uint32_t trackSampleRate, uint32_t devSampleRate) { - if (trackSampleRate != devSampleRate || resampler != NULL) { + if (trackSampleRate != devSampleRate || resampler != nullptr) { if (sampleRate != trackSampleRate) { sampleRate = trackSampleRate; - if (resampler == NULL) { + if (resampler == nullptr) { ALOGV("Creating resampler from track %d Hz to device %d Hz", trackSampleRate, devSampleRate); AudioResampler::src_quality quality; @@ -758,9 +758,9 @@ bool AudioMixer::track_t::setResampler(uint32_t trackSampleRate, uint32_t devSam // REFINE: Remove MONO_HACK. Resampler sees #channels after the downmixer // but if none exists, it is the channel count (1 for mono). - const int resamplerChannelCount = false /*downmixerBufferProvider != NULL*/ - ? mMixerChannelCount - : channelCount; + const int resamplerChannelCount = false /*downmixerBufferProvider != nullptr*/ + ? static_cast(mMixerChannelCount) + : static_cast(channelCount); ALOGVV( "Creating resampler:" " format(%#x) channels(%d) devSampleRate(%u) quality(%d)\n", @@ -778,17 +778,17 @@ bool AudioMixer::track_t::setResampler(uint32_t trackSampleRate, uint32_t devSam } bool AudioMixer::track_t::setPlaybackRate(const AudioPlaybackRate &playbackRate) { - //cjh if ((mTimestretchBufferProvider == NULL && + //cjh if ((mTimestretchBufferProvider == nullptr && // fabs(playbackRate.mSpeed - mPlaybackRate.mSpeed) < AUDIO_TIMESTRETCH_SPEED_MIN_DELTA && // fabs(playbackRate.mPitch - mPlaybackRate.mPitch) < AUDIO_TIMESTRETCH_PITCH_MIN_DELTA) || // isAudioPlaybackRateEqual(playbackRate, mPlaybackRate)) { // return false; // } mPlaybackRate = playbackRate; - // if (mTimestretchBufferProvider == NULL) { + // if (mTimestretchBufferProvider == nullptr) { // // REFINE: Remove MONO_HACK. Resampler sees #channels after the downmixer // // but if none exists, it is the channel count (1 for mono). - // const int timestretchChannelCount = downmixerBufferProvider != NULL + // const int timestretchChannelCount = downmixerBufferProvider != nullptr // ? mMixerChannelCount : channelCount; // mTimestretchBufferProvider = ccnew TimestretchBufferProvider(timestretchChannelCount, // mMixerInFormat, sampleRate, playbackRate); @@ -857,7 +857,7 @@ inline void AudioMixer::track_t::adjustVolumeRamp(bool aux, bool useFloat) { size_t AudioMixer::getUnreleasedFrames(int name) const { name -= TRACK0; - if (uint32_t(name) < MAX_NUM_TRACKS) { + if (static_cast(name) < MAX_NUM_TRACKS) { return mState.tracks[name].getUnreleasedFrames(); } return 0; @@ -870,13 +870,13 @@ void AudioMixer::setBufferProvider(int name, AudioBufferProvider *bufferProvider if (mState.tracks[name].mInputBufferProvider == bufferProvider) { return; // don't reset any buffer providers if identical. } - //cjh if (mState.tracks[name].mReformatBufferProvider != NULL) { + //cjh if (mState.tracks[name].mReformatBufferProvider != nullptr) { // mState.tracks[name].mReformatBufferProvider->reset(); - // } else if (mState.tracks[name].downmixerBufferProvider != NULL) { + // } else if (mState.tracks[name].downmixerBufferProvider != nullptr) { // mState.tracks[name].downmixerBufferProvider->reset(); - // } else if (mState.tracks[name].mPostDownmixReformatBufferProvider != NULL) { + // } else if (mState.tracks[name].mPostDownmixReformatBufferProvider != nullptr) { // mState.tracks[name].mPostDownmixReformatBufferProvider->reset(); - // } else if (mState.tracks[name].mTimestretchBufferProvider != NULL) { + // } else if (mState.tracks[name].mTimestretchBufferProvider != nullptr) { // mState.tracks[name].mTimestretchBufferProvider->reset(); // } @@ -888,7 +888,7 @@ void AudioMixer::process(int64_t pts) { mState.hook(&mState, pts); } -void AudioMixer::process__validate(state_t *state, int64_t pts) { +void AudioMixer::process__validate(state_t *state, int64_t pts) {//NOLINT ALOGW_IF(!state->needsChanged, "in process__validate() but nothing's invalid"); @@ -929,7 +929,7 @@ void AudioMixer::process__validate(state_t *state, int64_t pts) { if (t.doesResample()) { n |= NEEDS_RESAMPLE; } - if (t.auxLevel != 0 && t.auxBuffer != NULL) { + if (t.auxLevel != 0 && t.auxBuffer != nullptr) { n |= NEEDS_AUX; } @@ -988,11 +988,11 @@ void AudioMixer::process__validate(state_t *state, int64_t pts) { } else { if (state->outputTemp) { delete[] state->outputTemp; - state->outputTemp = NULL; + state->outputTemp = nullptr; } if (state->resampleTemp) { delete[] state->resampleTemp; - state->resampleTemp = NULL; + state->resampleTemp = nullptr; } state->hook = process__genericNoResampling; if (all16BitsStereoNoResample && !volumeRamp) { @@ -1051,13 +1051,13 @@ void AudioMixer::process__validate(state_t *state, int64_t pts) { } } -void AudioMixer::track__genericResample(track_t *t, int32_t *out, size_t outFrameCount, +void AudioMixer::track__genericResample(track_t *t, int32_t *out, size_t outFrameCount,//NOLINT int32_t *temp, int32_t *aux) { ALOGVV("track__genericResample\n"); t->resampler->setSampleRate(t->sampleRate); // ramp gain - resample to temp buffer and scale/mix in 2nd step - if (aux != NULL) { + if (aux != nullptr) { // always resample with unity gain when sending to auxiliary buffer to be able // to apply send level after resampling t->resampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT); @@ -1084,7 +1084,7 @@ void AudioMixer::track__genericResample(track_t *t, int32_t *out, size_t outFram } } -void AudioMixer::track__nop(track_t *t __unused, int32_t *out __unused, +void AudioMixer::track__nop(track_t *t __unused, int32_t *out __unused,//NOLINT size_t outFrameCount __unused, int32_t *temp __unused, int32_t *aux __unused) { } @@ -1100,7 +1100,7 @@ void AudioMixer::volumeRampStereo(track_t *t, int32_t *out, size_t frameCount, i // (vl + vlInc*frameCount)/65536.0f, frameCount); // ramp volume - if (CC_UNLIKELY(aux != NULL)) { + if (CC_UNLIKELY(aux != nullptr)) { int32_t va = t->prevAuxLevel; const int32_t vaInc = t->auxInc; int32_t l; @@ -1127,7 +1127,7 @@ void AudioMixer::volumeRampStereo(track_t *t, int32_t *out, size_t frameCount, i } t->prevVolume[0] = vl; t->prevVolume[1] = vr; - t->adjustVolumeRamp(aux != NULL); + t->adjustVolumeRamp(aux != nullptr); } void AudioMixer::volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp, @@ -1135,13 +1135,13 @@ void AudioMixer::volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32 const int16_t vl = t->volume[0]; const int16_t vr = t->volume[1]; - if (CC_UNLIKELY(aux != NULL)) { + if (CC_UNLIKELY(aux != nullptr)) { const int16_t va = t->auxLevel; do { - int16_t l = (int16_t)(*temp++ >> 12); - int16_t r = (int16_t)(*temp++ >> 12); + auto l = static_cast(*temp++ >> 12); + auto r = static_cast(*temp++ >> 12); out[0] = mulAdd(l, vl, out[0]); - int16_t a = (int16_t)(((int32_t)l + r) >> 1); + auto a = static_cast((static_cast(l) + r) >> 1); out[1] = mulAdd(r, vr, out[1]); out += 2; aux[0] = mulAdd(a, va, aux[0]); @@ -1149,8 +1149,8 @@ void AudioMixer::volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32 } while (--frameCount); } else { do { - int16_t l = (int16_t)(*temp++ >> 12); - int16_t r = (int16_t)(*temp++ >> 12); + auto l = static_cast(*temp++ >> 12); + auto r = static_cast(*temp++ >> 12); out[0] = mulAdd(l, vl, out[0]); out[1] = mulAdd(r, vr, out[1]); out += 2; @@ -1158,12 +1158,12 @@ void AudioMixer::volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32 } } -void AudioMixer::track__16BitsStereo(track_t *t, int32_t *out, size_t frameCount, +void AudioMixer::track__16BitsStereo(track_t *t, int32_t *out, size_t frameCount,//NOLINT int32_t *temp __unused, int32_t *aux) { ALOGVV("track__16BitsStereo\n"); - const int16_t *in = static_cast(t->in); + const auto *in = static_cast(t->in); - if (CC_UNLIKELY(aux != NULL)) { + if (CC_UNLIKELY(aux != nullptr)) { int32_t l; int32_t r; // ramp gain @@ -1179,8 +1179,8 @@ void AudioMixer::track__16BitsStereo(track_t *t, int32_t *out, size_t frameCount // (vl + vlInc*frameCount)/65536.0f, frameCount); do { - l = (int32_t)*in++; - r = (int32_t)*in++; + l = static_cast(*in++); + r = static_cast(*in++); *out++ += (vl >> 16) * l; *out++ += (vr >> 16) * r; *aux++ += (va >> 17) * (l + r); @@ -1198,10 +1198,10 @@ void AudioMixer::track__16BitsStereo(track_t *t, int32_t *out, size_t frameCount // constant gain else { const uint32_t vrl = t->volumeRL; - const int16_t va = (int16_t)t->auxLevel; + const auto va = t->auxLevel; do { uint32_t rl = *reinterpret_cast(in); - int16_t a = (int16_t)(((int32_t)in[0] + in[1]) >> 1); + auto a = static_cast((static_cast(in[0]) + in[1]) >> 1); in += 2; out[0] = mulAddRL(1, rl, vrl, out[0]); out[1] = mulAddRL(0, rl, vrl, out[1]); @@ -1223,8 +1223,8 @@ void AudioMixer::track__16BitsStereo(track_t *t, int32_t *out, size_t frameCount // (vl + vlInc*frameCount)/65536.0f, frameCount); do { - *out++ += (vl >> 16) * (int32_t)*in++; - *out++ += (vr >> 16) * (int32_t)*in++; + *out++ += (vl >> 16) * static_cast(*in++); + *out++ += (vr >> 16) * static_cast(*in++); vl += vlInc; vr += vrInc; } while (--frameCount); @@ -1249,12 +1249,12 @@ void AudioMixer::track__16BitsStereo(track_t *t, int32_t *out, size_t frameCount t->in = in; } -void AudioMixer::track__16BitsMono(track_t *t, int32_t *out, size_t frameCount, +void AudioMixer::track__16BitsMono(track_t *t, int32_t *out, size_t frameCount,//NOLINT int32_t *temp __unused, int32_t *aux) { ALOGVV("track__16BitsMono\n"); - const int16_t *in = static_cast(t->in); + const auto *in = static_cast(t->in); - if (CC_UNLIKELY(aux != NULL)) { + if (CC_UNLIKELY(aux != nullptr)) { // ramp gain if (CC_UNLIKELY(t->volumeInc[0] | t->volumeInc[1] | t->auxInc)) { int32_t vl = t->prevVolume[0]; @@ -1287,7 +1287,7 @@ void AudioMixer::track__16BitsMono(track_t *t, int32_t *out, size_t frameCount, else { const int16_t vl = t->volume[0]; const int16_t vr = t->volume[1]; - const int16_t va = (int16_t)t->auxLevel; + const auto va = t->auxLevel; do { int16_t l = *in++; out[0] = mulAdd(l, vl, out[0]); @@ -1337,13 +1337,14 @@ void AudioMixer::track__16BitsMono(track_t *t, int32_t *out, size_t frameCount, } // no-op case -void AudioMixer::process__nop(state_t *state, int64_t pts) { +void AudioMixer::process__nop(state_t *state, int64_t pts) {//NOLINT ALOGVV("process__nop\n"); uint32_t e0 = state->enabledTracks; while (e0) { // process by group of tracks with same output buffer to // avoid multiple memset() on same buffer - uint32_t e1 = e0, e2 = e0; + uint32_t e1 = e0; + uint32_t e2 = e0; int i = 31 - __builtin_clz(e1); { track_t &t1 = state->tracks[i]; @@ -1370,9 +1371,9 @@ void AudioMixer::process__nop(state_t *state, int64_t pts) { while (outFrames) { t3.buffer.frameCount = outFrames; int64_t outputPTS = calculateOutputPTS( - t3, pts, state->frameCount - outFrames); + t3, pts, state->frameCount - outFrames);//NOLINT t3.bufferProvider->getNextBuffer(&t3.buffer, outputPTS); - if (t3.buffer.raw == NULL) break; + if (t3.buffer.raw == nullptr) break; outFrames -= t3.buffer.frameCount; t3.bufferProvider->releaseBuffer(&t3.buffer); } @@ -1382,7 +1383,7 @@ void AudioMixer::process__nop(state_t *state, int64_t pts) { } // generic code without resampling -void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) { +void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) {//NOLINT ALOGVV("process__genericNoResampling\n"); int32_t outTemp[BLOCKSIZE * MAX_NUM_CHANNELS] __attribute__((aligned(32))); @@ -1403,7 +1404,8 @@ void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) { while (e0) { // process by group of tracks with same output buffer to // optimize cache use - uint32_t e1 = e0, e2 = e0; + uint32_t e1 = e0; + uint32_t e2 = e0; int j = 31 - __builtin_clz(e1); track_t &t1 = state->tracks[j]; e2 &= ~(1 << j); @@ -1427,14 +1429,14 @@ void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) { e2 &= ~(1 << i); track_t &t = state->tracks[i]; size_t outFrames = BLOCKSIZE; - int32_t *aux = NULL; + int32_t *aux = nullptr; if (CC_UNLIKELY(t.needs & NEEDS_AUX)) { aux = t.auxBuffer + numFrames; } while (outFrames) { - // t.in == NULL can happen if the track was flushed just after having + // t.in == nullptr can happen if the track was flushed just after having // been enabled for mixing. - if (t.in == NULL) { + if (t.in == nullptr) { enabledTracks &= ~(1 << i); e1 &= ~(1 << i); break; @@ -1445,7 +1447,7 @@ void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) { inFrames, state->resampleTemp, aux); t.frameCount -= inFrames; outFrames -= inFrames; - if (CC_UNLIKELY(aux != NULL)) { + if (CC_UNLIKELY(aux != nullptr)) { aux += inFrames; } } @@ -1454,10 +1456,10 @@ void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) { t.buffer.frameCount = (state->frameCount - numFrames) - (BLOCKSIZE - outFrames); int64_t outputPTS = calculateOutputPTS( - t, pts, numFrames + (BLOCKSIZE - outFrames)); + t, pts, numFrames + (BLOCKSIZE - outFrames));//NOLINT t.bufferProvider->getNextBuffer(&t.buffer, outputPTS); t.in = t.buffer.raw; - if (t.in == NULL) { + if (t.in == nullptr) { enabledTracks &= ~(1 << i); e1 &= ~(1 << i); break; @@ -1470,7 +1472,7 @@ void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) { convertMixerFormat(out, t1.mMixerFormat, outTemp, t1.mMixerInFormat, BLOCKSIZE * t1.mMixerChannelCount); // REFINE: fix ugly casting due to choice of out pointer type - out = reinterpret_cast((uint8_t *)out + BLOCKSIZE * t1.mMixerChannelCount * audio_bytes_per_sample(t1.mMixerFormat)); + out = reinterpret_cast(reinterpret_cast(out) + BLOCKSIZE * t1.mMixerChannelCount * audio_bytes_per_sample(t1.mMixerFormat)); numFrames += BLOCKSIZE; } while (numFrames < state->frameCount); } @@ -1486,7 +1488,7 @@ void AudioMixer::process__genericNoResampling(state_t *state, int64_t pts) { } // generic code with resampling -void AudioMixer::process__genericResampling(state_t *state, int64_t pts) { +void AudioMixer::process__genericResampling(state_t *state, int64_t pts) {//NOLINT ALOGVV("process__genericResampling\n"); // this const just means that local variable outTemp doesn't change int32_t *const outTemp = state->outputTemp; @@ -1496,7 +1498,8 @@ void AudioMixer::process__genericResampling(state_t *state, int64_t pts) { while (e0) { // process by group of tracks with same output buffer // to optimize cache use - uint32_t e1 = e0, e2 = e0; + uint32_t e1 = e0; + uint32_t e2 = e0; int j = 31 - __builtin_clz(e1); track_t &t1 = state->tracks[j]; e2 &= ~(1 << j); @@ -1515,7 +1518,7 @@ void AudioMixer::process__genericResampling(state_t *state, int64_t pts) { const int i = 31 - __builtin_clz(e1); e1 &= ~(1 << i); track_t &t = state->tracks[i]; - int32_t *aux = NULL; + int32_t *aux = nullptr; if (CC_UNLIKELY(t.needs & NEEDS_AUX)) { aux = t.auxBuffer; } @@ -1534,11 +1537,11 @@ void AudioMixer::process__genericResampling(state_t *state, int64_t pts) { int64_t outputPTS = calculateOutputPTS(t, pts, outFrames); t.bufferProvider->getNextBuffer(&t.buffer, outputPTS); t.in = t.buffer.raw; - // t.in == NULL can happen if the track was flushed just after having + // t.in == nullptr can happen if the track was flushed just after having // been enabled for mixing. - if (t.in == NULL) break; + if (t.in == nullptr) break; - if (CC_UNLIKELY(aux != NULL)) { + if (CC_UNLIKELY(aux != nullptr)) { aux += outFrames; } t.hook(&t, outTemp + outFrames * t.mMixerChannelCount, t.buffer.frameCount, @@ -1554,7 +1557,7 @@ void AudioMixer::process__genericResampling(state_t *state, int64_t pts) { } // one track, 16 bits stereo without resampling is the most common case -void AudioMixer::process__OneTrack16BitsStereoNoResampling(state_t *state, +void AudioMixer::process__OneTrack16BitsStereoNoResampling(state_t *state,//NOLINT int64_t pts) { ALOGVV("process__OneTrack16BitsStereoNoResampling\n"); // This method is only called when state->enabledTracks has exactly @@ -1568,7 +1571,7 @@ void AudioMixer::process__OneTrack16BitsStereoNoResampling(state_t *state, AudioBufferProvider::Buffer &b(t.buffer); int32_t *out = t.mainBuffer; - float *fout = reinterpret_cast(out); + auto *fout = reinterpret_cast(out); size_t numFrames = state->frameCount; const int16_t vl = t.volume[0]; @@ -1580,9 +1583,9 @@ void AudioMixer::process__OneTrack16BitsStereoNoResampling(state_t *state, t.bufferProvider->getNextBuffer(&b, outputPTS); const int16_t *in = b.i16; - // in == NULL can happen if the track was flushed just after having + // in == nullptr can happen if the track was flushed just after having // been enabled for mixing. - if (in == NULL || (((uintptr_t)in) & 3)) { + if (in == nullptr || (((uintptr_t)in) & 3)) {//NOLINT memset(out, 0, numFrames * t.mMixerChannelCount * audio_bytes_per_sample(t.mMixerFormat)); ALOGE_IF((((uintptr_t)in) & 3), "process__OneTrack16BitsStereoNoResampling: misaligned buffer" @@ -1662,8 +1665,7 @@ int64_t AudioMixer::calculateOutputPTS(const track_t &t, int64_t basePTS, // Needs to derive a compile time constant (constexpr). Could be targeted to go // to a MONOVOL mixtype based on MAX_NUM_VOLUMES, but that's an unnecessary complication. -#define MIXTYPE_MONOVOL(mixtype) (mixtype == MIXTYPE_MULTI ? MIXTYPE_MULTI_MONOVOL : mixtype == MIXTYPE_MULTI_SAVEONLY ? MIXTYPE_MULTI_SAVEONLY_MONOVOL \ - : mixtype) +#define MIXTYPE_MONOVOL(mixtype) (mixtype == MIXTYPE_MULTI ? MIXTYPE_MULTI_MONOVOL : mixtype == MIXTYPE_MULTI_SAVEONLY ? MIXTYPE_MULTI_SAVEONLY_MONOVOL : mixtype) /* MIXTYPE (see AudioMixerOps.h MIXTYPE_* enumeration) * TO: int32_t (Q4.27) or float @@ -1761,7 +1763,7 @@ void AudioMixer::volumeMix(TO *out, size_t outFrames, volumeRampMulti(t->mMixerChannelCount, out, outFrames, in, aux, t->mPrevVolume, t->mVolumeInc, &t->prevAuxLevel, t->auxInc); if (ADJUSTVOL) { - t->adjustVolumeRamp(aux != NULL, true); + t->adjustVolumeRamp(aux != nullptr, true); } } else { volumeMulti(t->mMixerChannelCount, out, outFrames, in, aux, @@ -1772,7 +1774,7 @@ void AudioMixer::volumeMix(TO *out, size_t outFrames, volumeRampMulti(t->mMixerChannelCount, out, outFrames, in, aux, t->prevVolume, t->volumeInc, &t->prevAuxLevel, t->auxInc); if (ADJUSTVOL) { - t->adjustVolumeRamp(aux != NULL); + t->adjustVolumeRamp(aux != nullptr); } } else { volumeMulti(t->mMixerChannelCount, out, outFrames, in, aux, @@ -1791,7 +1793,7 @@ void AudioMixer::volumeMix(TO *out, size_t outFrames, * TA: int32_t (Q4.27) */ template -void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) { +void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) {//NOLINT ALOGVV("process_NoResampleOneTrack\n"); // CLZ is faster than CTZ on ARM, though really not sure if true after 31 - clz. const int i = 31 - __builtin_clz(state->enabledTracks); @@ -1806,13 +1808,13 @@ void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) { AudioBufferProvider::Buffer &b(t->buffer); // get input buffer b.frameCount = numFrames; - const int64_t outputPTS = calculateOutputPTS(*t, pts, state->frameCount - numFrames); + const int64_t outputPTS = calculateOutputPTS(*t, pts, state->frameCount - numFrames);//NOLINT t->bufferProvider->getNextBuffer(&b, outputPTS); const TI *in = reinterpret_cast(b.raw); - // in == NULL can happen if the track was flushed just after having + // in == nullptr can happen if the track was flushed just after having // been enabled for mixing. - if (in == NULL || (((uintptr_t)in) & 3)) { + if (in == nullptr || (((uintptr_t)in) & 3)) {//NOLINT memset(out, 0, numFrames * channels * audio_bytes_per_sample(t->mMixerFormat)); ALOGE_IF((((uintptr_t)in) & 3), "process_NoResampleOneTrack: bus error: " @@ -1826,7 +1828,7 @@ void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) { out, outFrames, in, aux, ramp, t); out += outFrames * channels; - if (aux != NULL) { + if (aux != nullptr) { aux += channels; } numFrames -= b.frameCount; @@ -1835,7 +1837,7 @@ void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) { t->bufferProvider->releaseBuffer(&b); } if (ramp) { - t->adjustVolumeRamp(aux != NULL, is_same::value); + t->adjustVolumeRamp(aux != nullptr, is_same::value); } } @@ -1848,24 +1850,24 @@ void AudioMixer::process_NoResampleOneTrack(state_t *state, int64_t pts) { * TA: int32_t (Q4.27) */ template -void AudioMixer::track__Resample(track_t *t, TO *out, size_t outFrameCount, TO *temp, TA *aux) { +void AudioMixer::track__Resample(track_t *t, TO *out, size_t outFrameCount, TO *temp, TA *aux) {//NOLINT ALOGVV("track__Resample\n"); t->resampler->setSampleRate(t->sampleRate); const bool ramp = t->needsRamp(); - if (ramp || aux != NULL) { + if (ramp || aux != nullptr) { // if ramp: resample with unity gain to temp buffer and scale/mix in 2nd step. - // if aux != NULL: resample with unity gain to temp buffer then apply send level. + // if aux != nullptr: resample with unity gain to temp buffer then apply send level. t->resampler->setVolume(UNITY_GAIN_FLOAT, UNITY_GAIN_FLOAT); memset(temp, 0, outFrameCount * t->mMixerChannelCount * sizeof(TO)); - t->resampler->resample((int32_t *)temp, outFrameCount, t->bufferProvider); + t->resampler->resample((int32_t *)temp, outFrameCount, t->bufferProvider);//NOLINT volumeMix::value, true>( out, outFrameCount, temp, aux, ramp, t); } else { // constant volume gain t->resampler->setVolume(t->mVolume[0], t->mVolume[1]); - t->resampler->resample((int32_t *)out, outFrameCount, t->bufferProvider); + t->resampler->resample((int32_t *)out, outFrameCount, t->bufferProvider);//NOLINT } } @@ -1878,7 +1880,7 @@ void AudioMixer::track__Resample(track_t *t, TO *out, size_t outFrameCount, TO * * TA: int32_t (Q4.27) */ template -void AudioMixer::track__NoResample(track_t *t, TO *out, size_t frameCount, +void AudioMixer::track__NoResample(track_t *t, TO *out, size_t frameCount,//NOLINT TO *temp __unused, TA *aux) { ALOGVV("track__NoResample\n"); const TI *in = static_cast(t->in); @@ -1905,7 +1907,7 @@ void AudioMixer::convertMixerFormat(void *out, audio_format_t mixerOutFormat, memcpy(out, in, sampleCount * sizeof(float)); // MEMCPY. REFINE: optimize out break; case AUDIO_FORMAT_PCM_16_BIT: - memcpy_to_i16_from_float((int16_t *)out, (float *)in, sampleCount); + memcpy_to_i16_from_float(static_cast(out), static_cast(in), sampleCount); break; default: LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat); @@ -1915,11 +1917,11 @@ void AudioMixer::convertMixerFormat(void *out, audio_format_t mixerOutFormat, case AUDIO_FORMAT_PCM_16_BIT: switch (mixerOutFormat) { case AUDIO_FORMAT_PCM_FLOAT: - memcpy_to_float_from_q4_27((float *)out, (int32_t *)in, sampleCount); + memcpy_to_float_from_q4_27(static_cast(out), static_cast(in), sampleCount); break; case AUDIO_FORMAT_PCM_16_BIT: // two int16_t are produced per iteration - ditherAndClamp((int32_t *)out, (int32_t *)in, sampleCount >> 1); + ditherAndClamp(static_cast(out), static_cast(in), sampleCount >> 1); break; default: LOG_ALWAYS_FATAL("bad mixerOutFormat: %#x", mixerOutFormat); @@ -1958,11 +1960,9 @@ AudioMixer::hook_t AudioMixer::getTrackHook(int trackType, uint32_t channelCount case TRACKTYPE_RESAMPLE: switch (mixerInFormat) { case AUDIO_FORMAT_PCM_FLOAT: - return (AudioMixer::hook_t) - track__Resample; + return reinterpret_cast(track__Resample); case AUDIO_FORMAT_PCM_16_BIT: - return (AudioMixer::hook_t) - track__Resample; + return static_cast(track__Resample); default: LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat); break; @@ -1971,11 +1971,9 @@ AudioMixer::hook_t AudioMixer::getTrackHook(int trackType, uint32_t channelCount case TRACKTYPE_NORESAMPLEMONO: switch (mixerInFormat) { case AUDIO_FORMAT_PCM_FLOAT: - return (AudioMixer::hook_t) - track__NoResample; + return reinterpret_cast(track__NoResample); case AUDIO_FORMAT_PCM_16_BIT: - return (AudioMixer::hook_t) - track__NoResample; + return static_cast(track__NoResample); default: LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat); break; @@ -1984,11 +1982,9 @@ AudioMixer::hook_t AudioMixer::getTrackHook(int trackType, uint32_t channelCount case TRACKTYPE_NORESAMPLE: switch (mixerInFormat) { case AUDIO_FORMAT_PCM_FLOAT: - return (AudioMixer::hook_t) - track__NoResample; + return reinterpret_cast(track__NoResample); case AUDIO_FORMAT_PCM_16_BIT: - return (AudioMixer::hook_t) - track__NoResample; + return static_cast(track__NoResample); default: LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat); break; @@ -1998,7 +1994,7 @@ AudioMixer::hook_t AudioMixer::getTrackHook(int trackType, uint32_t channelCount LOG_ALWAYS_FATAL("bad trackType: %d", trackType); break; } - return NULL; + return nullptr; } /* Returns the proper process hook for mixing tracks. Currently works only for @@ -2012,7 +2008,7 @@ AudioMixer::process_hook_t AudioMixer::getProcessHook(int processType, uint32_t audio_format_t mixerInFormat, audio_format_t mixerOutFormat) { if (processType != PROCESSTYPE_NORESAMPLEONETRACK) { // Only NORESAMPLEONETRACK LOG_ALWAYS_FATAL("bad processType: %d", processType); - return NULL; + return nullptr; } if (!kUseNewMixer && channelCount == FCC_2 && mixerInFormat == AUDIO_FORMAT_PCM_16_BIT) { return process__OneTrack16BitsStereoNoResampling; @@ -2049,7 +2045,7 @@ AudioMixer::process_hook_t AudioMixer::getProcessHook(int processType, uint32_t LOG_ALWAYS_FATAL("bad mixerInFormat: %#x", mixerInFormat); break; } - return NULL; + return nullptr; } // ---------------------------------------------------------------------------- diff --git a/native/cocos/audio/android/AudioResampler.cpp b/native/cocos/audio/android/AudioResampler.cpp index 8157843fc4..32e23c4152 100644 --- a/native/cocos/audio/android/AudioResampler.cpp +++ b/native/cocos/audio/android/AudioResampler.cpp @@ -26,7 +26,7 @@ #include "audio/android/utils/Utils.h" //#include #include "audio/android/AudioResampler.h" -#include "audio/android/audio_utils/include/audio_utils/primitives.h" +#include "audio/common/utils/include/primitives.h" //#include "audio/android/AudioResamplerSinc.h" #include "audio/android/AudioResamplerCubic.h" #include "base/memory/Memory.h" diff --git a/native/cocos/audio/android/IVolumeProvider.h b/native/cocos/audio/android/IVolumeProvider.h index 4076ceb39e..c1b49a71d7 100644 --- a/native/cocos/audio/android/IVolumeProvider.h +++ b/native/cocos/audio/android/IVolumeProvider.h @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ #pragma once -#include "audio/android/audio_utils/include/audio_utils/minifloat.h" +#include "audio/common/utils/include/minifloat.h" namespace cc { diff --git a/native/cocos/audio/oalsoft/AudioDecoder.cpp b/native/cocos/audio/common/decoder/AudioDecoder.cpp similarity index 94% rename from native/cocos/audio/oalsoft/AudioDecoder.cpp rename to native/cocos/audio/common/decoder/AudioDecoder.cpp index d2c2c8c15e..463f958222 100644 --- a/native/cocos/audio/oalsoft/AudioDecoder.cpp +++ b/native/cocos/audio/common/decoder/AudioDecoder.cpp @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ -#include "audio/oalsoft/AudioDecoder.h" -#include -#include -#include "audio/oalsoft/AudioMacros.h" +#include +#include +#include "audio/common/decoder/AudioDecoder.h" +#include "audio/include/AudioMacros.h" #include "platform/FileUtils.h" #ifdef LOG_TAG @@ -40,8 +40,7 @@ namespace cc { AudioDecoder::AudioDecoder() : _isOpened(false) {} -AudioDecoder::~AudioDecoder() { -} +AudioDecoder::~AudioDecoder() = default; bool AudioDecoder::isOpened() const { return _isOpened; diff --git a/native/cocos/audio/oalsoft/AudioDecoder.h b/native/cocos/audio/common/decoder/AudioDecoder.h similarity index 99% rename from native/cocos/audio/oalsoft/AudioDecoder.h rename to native/cocos/audio/common/decoder/AudioDecoder.h index ded2714c8d..b05841db4e 100644 --- a/native/cocos/audio/oalsoft/AudioDecoder.h +++ b/native/cocos/audio/common/decoder/AudioDecoder.h @@ -29,7 +29,7 @@ #include #include -#include