Compare commits

...

53 Commits

Author SHA1 Message Date
hyde zhou 68552314c0 bump version to 4.0.0-alpha.32 (#320) 2026-09-01 21:13:19 +08:00
zxx43 550eb15641 add line updateColor function (#317)
* add line setColor function

* fix eslint

* modify setColor to updateColor
2026-08-31 11:56:37 +08:00
Ming c438c2d3f8 fix(rendering): compute render pass merge info in render graph order (#314) 2026-08-29 17:39:20 +08:00
zxx43 f5eaf97ce7 add opacity calculation to Particle System 2D (#307)
* add opacity calculation to Particle System 2D

* modify format
2026-08-25 18:37:08 +08:00
zxx43 69d3d6033a fix message error (#304) 2026-08-24 11:13:30 +08:00
yangchao 469614cf0b fix ios build problem (#292) 2026-08-23 12:01:54 +08:00
Cocos Robot f81094f226 [ci skip][AUTO]: Automated clang-format update: 6c156997c2 (#293) (#301)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-23 11:07:26 +08:00
Ming 825362fac1 fix(webgl): correct buffer-to-texture extent height calculation (#303)
Use regionTexExtentHeight instead of regionTexExtentWidth when calculating copied texture extents to prevent incorrect row and slice strides.

Co-authored-by: vanitynie <vanitynie@qq.com>
2026-08-21 12:27:25 +08:00
ChiaNing 609512f8da fix(ui):keep destroy widgets out of the widget's active list (#302) 2026-08-21 10:04:48 +08:00
troublemaker52025 09b63786f4 fix(legacy): sync instanced buffer batching optimization to native (#293) 2026-08-20 15:56:12 +08:00
MagicXHouse 2b7b438768 Fix: Fixed the issue where custom pipeline profiler were not displaying. (#295) 2026-08-20 11:26:22 +08:00
xubing0906 6b5c8556a2 Fix Builtin reflection probe culling by passing the probe context to … (#186) 2026-08-19 17:25:21 +08:00
昌敦伟 ff436d6a27 fix: balance Texture2D image dependency references (#267) 2026-08-19 16:05:59 +08:00
hyde zhou 09c38ea03f bump version to 4.0.0-alpha.31 (#290) 2026-08-17 17:53:49 +08:00
qiuguohua 926bd5b619 chore(platform): privatize platform; migrate to platform subrepo (#289) 2026-08-17 17:26:19 +08:00
徐兵 e317c04512 fix planar reflections for editor camera previews (#236) 2026-08-17 17:25:14 +08:00
Cocos Robot 140068ddb1 [ci skip][AUTO]: Automated code generating update: 233020bafe (#287) (#288)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 18:22:23 +08:00
hyde zhou 80a9d0619e ignore cocos-version.h (#287) 2026-08-16 18:17:09 +08:00
Cocos Robot a01046e391 [ci skip][AUTO]: Automated clang-format update: 25bf4eb07b (#284) (#285)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 17:13:20 +08:00
Cocos Robot 2b6ec3b4f0 [ci skip][AUTO]: Automated code generating update: cdd07414a3 (#278) (#284)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 17:07:21 +08:00
Cocos Robot 6060f58d1a [ci skip][AUTO]: Automated clang-format update: 3a76374539 (#277) (#278)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 17:01:44 +08:00
hyde zhou 18456b6706 try fixing previous clang format ignore (#277) 2026-08-15 23:32:02 +08:00
hyde zhou 62b55a0c48 Revert "fix: exclude spine 4.2 third-party files from clang-format (#273)" (#275)
This reverts commit 01983b75f2.
2026-08-15 20:17:08 +08:00
Copilot 0eac18be1a Fix Clang-Format workflow failure caused by shallow checkout state (#274)
* Initial plan

* Fix Clang-Format workflow shallow fetch failure

Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>
2026-08-15 19:50:32 +08:00
Copilot 01983b75f2 fix: exclude spine 4.2 third-party files from clang-format (#273) 2026-08-15 18:34:08 +08:00
jk20012001 2d003cc616 fix punctual lights visibility issue with custom pipeline (#270) (#272) 2026-08-15 15:36:26 +08:00
zxx43 b710cb6e9b fix both null condition (#260)
* fix both null condition

* simplify check condition

* simplify check condition
2026-08-14 17:21:26 +08:00
llsansun f948b5900e perf: optimize instanced buffer batching (#269)
* perf: optimize instanced buffer batching

* perf: reduce instanced buffer optimization code size

* perf: reduce instanced buffer optimization code size

* perf: reduce instanced buffer optimization code size
2026-08-14 16:44:35 +08:00
zxx43 b7883f18ba fix boneIdx check error (#264)
* fix boneIdx check error

* simplify check
2026-08-14 16:41:08 +08:00
troublemaker52025 3ab299035a fix(legacy): Mask component stencil test error for native (#266) 2026-08-14 15:49:57 +08:00
zxx43 c2ab919e9d fix native crash by null material bug (#268) 2026-08-14 15:38:17 +08:00
qiuguohua 5690d1b8a5 fix(google-play): set PROP_MIN_SDK_VERSION to 24 (#262)
play-services-oss-licenses, introduced on Feb 2, 2026, requires minSdkVersion 24.
https://developers.google.com/android/guides/releases
2026-08-11 19:35:31 +08:00
hyde zhou ed0751652b bump version to 4.0.0-alpha.30 (#259) 2026-08-08 20:33:50 +08:00
hyde zhou 97e402c3dc Merge pull request #255 from cocos/v4.0.0-alpha.29
update version, fix libwebp compile err. (#247)
2026-08-08 17:44:37 +08:00
Copilot f378a866cb Fix Clang-Format CI: replace distutils-dependent action with maintained upstream (#257)
* Initial plan

* Fix Clang-Format CI: replace fish9167/clang-format-lint-action@master with DoozyX/clang-format-lint-action@v0.18

Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>
2026-08-08 17:44:10 +08:00
Copilot 7253ee4a7f Fix ESLint CI job failure on tag push events (#256) 2026-08-08 16:59:07 +08:00
hyde zhou db5462603e Move pal directory to private repository (#191) (#254)
Co-authored-by: qiuguohua <qiuguohua111@126.com>
2026-08-08 16:20:49 +08:00
zxx43 9f0e30acb3 add approx functions (#252) 2026-08-07 18:40:33 +08:00
troublemaker52025 a0a2e97c00 fix(legacy): A2C (Alpha to Coverage) and (antialias or MSAA) are mutually exclusive (#233) 2026-08-07 16:27:27 +08:00
troublemaker52025 90e551b4a1 fix(legacy): the incorrect description of light visibility (#251) 2026-08-07 16:24:00 +08:00
Ming 0a21bb9397 fix(vulkan): fix split barrier events and general barrier submission (#240) 2026-08-07 16:03:46 +08:00
troublemaker52025 2c91155928 fix(legacy): sphere light has not lighting at LDR mode (#243) 2026-08-07 15:20:25 +08:00
llsansun 6f90cec3d4 Merge pull request #245 from zxx43/LogFix
modify success log level from loge to logd
2026-08-05 18:51:56 +08:00
yangchao 4992692780 update version, fix libwebp compile err. (#247) 2026-08-05 16:11:33 +08:00
徐兵 d5f24e6170 Merge pull request #246 from xubing0906/v4.0.0-skybox
fix(rendering): skip environment specular sampling when IBL is disabled in reflection probe fallback
2026-08-05 16:00:31 +08:00
zxx43 e778833d15 modify success log level from loge to logd 2026-08-05 12:05:12 +08:00
hyde zhou c3a8a72f63 bump version to 4.0.0-alpha.29 (#237) 2026-08-02 21:25:47 +08:00
yangchao 2c0e75059f xcode > 14.3 apple silicon use arm64 arch for ios simulation。 (#214) 2026-08-02 17:52:06 +08:00
zxx43 19f4bd5b16 call ClearMaterialCaches when change tint state (#234) 2026-07-31 17:24:28 +08:00
徐兵 085d05928d fix(shader): fix lighting discontinuity at mirrored UV seams (#209) 2026-07-31 17:19:29 +08:00
Tianze-Chen fb4d586629 fix(2d): retain Graphics data while disabled (#230) 2026-07-31 17:03:55 +08:00
troublemaker52025 620d38cf42 Fix(legacy): only DEFAULT layer has lighting (#227) 2026-07-31 16:49:41 +08:00
zxx43 d2713fe00e fix loop duration time (#213) 2026-07-31 16:39:08 +08:00
738 changed files with 4107 additions and 57944 deletions
+8 -2
View File
@@ -20,8 +20,14 @@ if ($env:GITHUB_BASE_REF) {
# Push
$gitHubEvent = Get-Content $env:GITHUB_EVENT_PATH | ConvertFrom-Json
Write-Host "GitHub event: $gitHubEvent"
git fetch origin $gitHubEvent.before --depth=1
$diffFiles = git diff --name-only --diff-filter=$diffFilter $gitHubEvent.before $env:GITHUB_SHA
$beforeSha = $gitHubEvent.before
# On tag creation or initial push, before is all zeros - skip diff in that case
if ($beforeSha -match '^0+$') {
Write-Host "No previous commit (tag creation or initial push). Skipping diff."
return
}
git fetch origin $beforeSha --depth=1
$diffFiles = git diff --name-only --diff-filter=$diffFilter $beforeSha $env:GITHUB_SHA
}
Write-Host "Diff files: $diffFiles"
+4 -8
View File
@@ -18,6 +18,7 @@ jobs:
with:
token: ${{ github.token }}
ref: ${{ github.head_sha }}
fetch-depth: 0
- id: get_change_files
uses: fish9167/file-changes-action@v1.2.3
@@ -25,18 +26,13 @@ jobs:
output: ' '
fileOutput: ' '
- name: Echo change files
run: |
cat $HOME/files.txt
mv $HOME/files.txt ${{github.workspace}}/files.txt
- uses: fish9167/clang-format-lint-action@master
- uses: DoozyX/clang-format-lint-action@v0.18
with:
source: ./native
exclude: ./native/cocos/bindings/auto
exclude: ./native/cocos/bindings/auto ./native/cocos/base/std ./native/cocos/editor-support/spine-wasm ./native/cocos/editor-support/spine ./native/cocos/gi/light-probe/predicates.cpp ./native/cocos/gi/light-probe/tetgen.cpp ./native/cocos/gi/light-probe/tetgen.h ./native/cocos/platform/openharmony/napi ./native/tools ./native/vendor ./native/cocos/cocos-version.h
extensions: 'c,h,hpp,cpp,cxx'
style: file
inplace: True
inplace: true
clangFormatVersion: 12
- name: Create Pull Request
@@ -483,8 +483,8 @@ jobs:
echo "set(CC_USE_GLES3 OFF)" >> build-mac/proj/cfg.cmake
echo "set(CC_USE_METAL ON)" >> build-mac/proj/cfg.cmake
# Test JSVM v8 backend on macOS.
echo "set(USE_SE_V8 OFF)" >> build-mac/proj/cfg.cmake
echo "set(USE_SE_JSVM ON)" >> build-mac/proj/cfg.cmake
echo "set(USE_SE_V8 ON)" >> build-mac/proj/cfg.cmake
echo "set(USE_SE_JSVM OFF)" >> build-mac/proj/cfg.cmake
echo "set(USE_WEBSOCKET_SERVER OFF)" >> build-mac/proj/cfg.cmake
echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-mac/proj/cfg.cmake
echo "set(CC_EXECUTABLE_NAME \"\")" >> build-mac/proj/cfg.cmake
@@ -493,7 +493,6 @@ jobs:
RES_DIR=$GITHUB_WORKSPACE/templates/mac/build-mac
cd build-mac
cmake ../ -GXcode -DCMAKE_OSX_ARCHITECTURES=${{ matrix.config.arch }} -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$NATIVE_ROOT
set +e
cmake --build . --config Release -- -jobs $NUM_OF_CORES -arch ${{ matrix.config.arch }}
echo "Compile MacOSX Release Done!"
@@ -534,7 +533,7 @@ jobs:
echo "set(CC_USE_VULKAN OFF)" >> build-ios/proj/cfg.cmake
echo "set(CC_USE_GLES2 OFF)" >> build-ios/proj/cfg.cmake
echo "set(CC_USE_METAL ON)" >> build-ios/proj/cfg.cmake
echo "set(TARGET_IOS_VERSION 12.0)" >> build-ios/proj/cfg.cmake
echo "set(TARGET_IOS_VERSION 13.0)" >> build-ios/proj/cfg.cmake
echo "set(USE_WEBSOCKET_SERVER OFF)" >> build-ios/proj/cfg.cmake
echo "set(USE_DRAGONBONES OFF)" >> build-ios/proj/cfg.cmake
echo "set(CMAKE_CXX_STANDARD_REQUIRED OFF)" >> build-ios/proj/cfg.cmake
@@ -548,7 +547,6 @@ jobs:
-DCMAKE_OSX_ARCHITECTURES=${{ matrix.config.arch }} \
-DRES_DIR=$RES_DIR \
-DCOCOS_X_PATH=$NATIVE_ROOT
set +e
#cmake --build . --config Debug -- -quiet -jobs $NUM_OF_CORES -allowProvisioningUpdates CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO
cmake --build . --config Debug -- -jobs $NUM_OF_CORES CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO
echo "Compile iOS Done!"
+1
View File
@@ -28,6 +28,7 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
- run: npm ci --ignore-scripts
- run: node scripts/spread-pal.cjs
- run: npm run build:debug-infos
- name: Download external
run: |
+8
View File
@@ -46,3 +46,11 @@ platforms/runtime/platforms/vivo-mini-game/ral.min.js
@types/consts.d.ts
__TS_ENGINE__/
# pal 由 @cocos/engine-pal 在 postinstall 挂载(软链/复制),不入库
/pal
# platforms 源码已抽到 @cocos/engine-platforms;其预打包 adapter 由 postinstall 的
# spread-adapter.cjs 复制到 bin/adapter(/bin 已忽略)。platforms 源码不再入库。
/platforms
+4
View File
@@ -3980,3 +3980,7 @@ Debug bones or slots is invalid in cached mode.
### 16419
Spine version not supported.
### 16420
End time must bigger than start time.
+44 -44
View File
@@ -382,70 +382,70 @@
"test": "context.buildTimeConstants && context.buildTimeConstants.HTML5",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/non-minigame.ts",
"pal/audio": "pal/audio/web/player.ts",
"pal/system-info": "pal/system-info/web/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.ts",
"pal/input": "pal/input/web/index.ts",
"pal/env": "pal/env/web/env.ts",
"pal/pacer": "pal/pacer/pacer-web.ts",
"pal/wasm": "pal/wasm/wasm-web.ts"
"pal/minigame": "pal/minigame/non-minigame.js",
"pal/audio": "pal/audio/web/player.js",
"pal/system-info": "pal/system-info/web/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.js",
"pal/input": "pal/input/web/index.js",
"pal/env": "pal/env/web/env.js",
"pal/pacer": "pal/pacer/pacer-web.js",
"pal/wasm": "pal/wasm/wasm-web.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.NATIVE",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/non-minigame.ts",
"pal/audio": "pal/audio/native/player.ts",
"pal/system-info": "pal/system-info/native/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.ts",
"pal/input": "pal/input/native/index.ts",
"pal/env": "pal/env/native/env.ts",
"pal/pacer": "pal/pacer/pacer-native.ts",
"pal/wasm": "pal/wasm/wasm-native.ts"
"pal/minigame": "pal/minigame/non-minigame.js",
"pal/audio": "pal/audio/native/player.js",
"pal/system-info": "pal/system-info/native/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.js",
"pal/input": "pal/input/native/index.js",
"pal/env": "pal/env/native/env.js",
"pal/pacer": "pal/pacer/pacer-native.js",
"pal/wasm": "pal/wasm/wasm-native.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.MINIGAME",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.ts",
"pal/audio": "pal/audio/minigame/player.ts",
"pal/system-info": "pal/system-info/minigame/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
"pal/input": "pal/input/minigame/index.ts",
"pal/env": "pal/env/minigame/env.ts",
"pal/pacer": "pal/pacer/pacer-minigame.ts",
"pal/wasm": "pal/wasm/wasm-minigame.ts"
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.js",
"pal/audio": "pal/audio/minigame/player.js",
"pal/system-info": "pal/system-info/minigame/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
"pal/input": "pal/input/minigame/index.js",
"pal/env": "pal/env/minigame/env.js",
"pal/pacer": "pal/pacer/pacer-minigame.js",
"pal/wasm": "pal/wasm/wasm-minigame.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.RUNTIME_BASED",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/runtime.ts",
"pal/audio": "pal/audio/minigame/player.ts",
"pal/system-info": "pal/system-info/minigame/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
"pal/input": "pal/input/minigame/index.ts",
"pal/env": "pal/env/runtime/env.ts",
"pal/pacer": "pal/pacer/pacer-minigame.ts",
"pal/wasm": "pal/wasm/wasm-minigame.ts"
"pal/minigame": "pal/minigame/runtime.js",
"pal/audio": "pal/audio/minigame/player.js",
"pal/system-info": "pal/system-info/minigame/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
"pal/input": "pal/input/minigame/index.js",
"pal/env": "pal/env/runtime/env.js",
"pal/pacer": "pal/pacer/pacer-minigame.js",
"pal/wasm": "pal/wasm/wasm-minigame.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.NODEJS",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/non-minigame.ts",
"pal/audio": "pal/audio/nodejs/player.ts",
"pal/system-info": "pal/system-info/nodejs/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.ts",
"pal/input": "pal/input/nodejs/index.ts",
"pal/env": "pal/env/nodejs/env.ts",
"pal/pacer": "pal/pacer/pacer-nodejs.ts",
"pal/wasm": "pal/wasm/wasm-nodejs.ts"
"pal/minigame": "pal/minigame/non-minigame.js",
"pal/audio": "pal/audio/nodejs/player.js",
"pal/system-info": "pal/system-info/nodejs/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.js",
"pal/input": "pal/input/nodejs/index.js",
"pal/env": "pal/env/nodejs/env.js",
"pal/pacer": "pal/pacer/pacer-nodejs.js",
"pal/wasm": "pal/wasm/wasm-nodejs.js"
}
},
{
@@ -885,10 +885,10 @@
"cocos/asset/asset-manager/weak-cache.ts",
"cocos/2d/framework/ui-skew-utils.ts",
"cocos/spine/lib/spine-binary.ts",
"pal/input/minigame/gamepad-input.ts",
"pal/input/minigame/handheld-input.ts",
"pal/input/minigame/handle-input.ts",
"pal/input/minigame/hmd-input.ts"
"pal/input/minigame/gamepad-input.js",
"pal/input/minigame/handheld-input.js",
"pal/input/minigame/handle-input.js",
"pal/input/minigame/hmd-input.js"
]
}
}
+9
View File
@@ -266,6 +266,15 @@ export class Graphics extends UIRenderer {
this._updateMtlForGraphics();
}
protected override get _keepRenderData (): boolean {
// Graphics is a retained-mode renderer: its MeshRenderData is the result of the
// user's previous fill()/stroke() calls. Destroying it here would leave Impl's
// render-data list pointing at cleared geometry, so re-enabling the node on native
// platforms would require the user to draw the paths again. Keep it attached to the
// disabled RenderEntity; clear() and onDestroy() remain the owning release points.
return true;
}
public onDestroy (): void {
this._sceneGetter = null;
if (JSB) {
+12 -1
View File
@@ -398,12 +398,23 @@ export class UIRenderer extends Renderer {
this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
this.destroyRenderData();
if (!this._keepRenderData) {
this.destroyRenderData();
}
uiRendererManager.removeRenderer(this);
this._renderFlag = false;
this._renderEntity.enabled = false;
}
/**
* Whether to keep render data when the component leaves the active hierarchy.
* Retained-mode renderers may override this policy and keep their render data until
* the content is explicitly cleared or the component is destroyed.
*/
protected get _keepRenderData (): boolean {
return false;
}
public onDestroy (): void {
this._renderEntity.setNode(null);
if (this.node._uiProps.uiComp === this) {
@@ -384,10 +384,10 @@ export class ReflectionProbe extends Component {
}
}
}
if (this.probeType === ProbeType.PLANAR && this.sourceCamera) {
if (!EDITOR_NOT_IN_PREVIEW && this.probeType === ProbeType.PLANAR && this.sourceCamera) {
if ((this.sourceCamera.node.hasChangedFlags & TransformBit.TRS)
|| !this._sourceCameraPos.equals(this.sourceCamera.node.getWorldPosition())) {
this._sourceCameraPos = this.sourceCamera.node.getWorldPosition();
this._sourceCameraPos.set(this.sourceCamera.node.getWorldPosition());
this.probe.renderPlanarReflection(this.sourceCamera.camera);
}
}
+3 -2
View File
@@ -76,10 +76,11 @@ simpleTextureProto._onGFXTextureUpdated = function (gfxTexture) {
simpleTextureProto._onAfterAssignImage = function (image) {
if (macro.CLEANUP_IMAGE_CACHE) {
const deps = dependUtil.getDeps(this._uuid);
const index = deps.indexOf(image._uuid);
if (index !== -1) {
let index = deps.indexOf(image._uuid);
while (index !== -1) {
js.array.fastRemoveAt(deps, index);
image.decRef();
index = deps.indexOf(image._uuid);
}
}
};
+4 -2
View File
@@ -194,10 +194,12 @@ export class SimpleTexture extends TextureBase {
if (macro.CLEANUP_IMAGE_CACHE) {
const deps = dependUtil.getDeps(this._uuid);
const index = deps.indexOf(image._uuid);
if (index !== -1) {
let index = deps.indexOf(image._uuid);
while (index !== -1) {
js.array.fastRemoveAt(deps, index);
image.decRef();
// The same UUID may occur more than once; find the next dependency edge.
index = deps.indexOf(image._uuid);
}
}
}
+52
View File
@@ -69,6 +69,58 @@ export function approx (a: number, b: number, maxDiff?: number): boolean {
return mathAbs(a - b) <= maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately greater than or equal to the second
* @zh 测试第一个参数是否近似大于或等于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately greater than or equal to b, false otherwise
*/
export function approxGE (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a >= b - maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately less than or equal to the second
* @zh 测试第一个参数是否近似小于或等于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately less than or equal to b, false otherwise
*/
export function approxLE (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a <= b + maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately greater than the second
* @zh 测试第一个参数是否近似大于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately greater than b, false otherwise
*/
export function approxGT (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a > b + maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately less than the second
* @zh 测试第一个参数是否近似小于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately less than b, false otherwise
*/
export function approxLT (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a < b - maxDiff;
}
/**
* @en Clamps a value between a minimum float and maximum float value.<br/>
* @zh 返回最小浮点数和最大浮点数之间的一个数值。可以使用 clamp 函数将不断变化的数值限制在范围内。
+2 -2
View File
@@ -2702,7 +2702,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
@@ -2773,7 +2773,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
+4 -4
View File
@@ -2811,7 +2811,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
@@ -2883,7 +2883,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
extent.depth = 1;
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
@@ -2965,7 +2965,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
offset.z = regionTexOffset.z;
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
extent.depth = regionTexExtent.depth;
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
@@ -3043,7 +3043,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
+27 -8
View File
@@ -52,6 +52,7 @@ class Particle {
public pos = new Vec2(0, 0);
public startPos = new Vec2(0, 0);
public color = new Color(0, 0, 0, 255);
public curColor = { r: 0, g: 0, b: 0, a: 255 };
public deltaColor = { r: 0, g: 0, b: 0, a: 255 };
public size = 0;
public deltaSize = 0;
@@ -81,6 +82,8 @@ const pool = new ParticlePool((par: Particle): void => {
par.pos.set(Vec2.ZERO);
par.startPos.set(Vec2.ZERO);
par.color.set(0, 0, 0, 255);
par.curColor.r = par.curColor.g = par.curColor.b = 0;
par.curColor.a = 255;
par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0;
par.deltaColor.a = 255;
par.size = 0;
@@ -111,6 +114,7 @@ export class Simulator {
private elapsed = 0;
private emitCounter = 0;
private _worldRotation = 0;
private _parentAlpha = 0.0;
private declare sys: ParticleSystem2D;
constructor (system) {
@@ -169,10 +173,10 @@ export class Simulator {
const endColor = psys.endColor;
const endColorVar = psys.endColorVar;
particle.color.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
particle.color.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
particle.color.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
particle.color.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
particle.curColor.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
particle.curColor.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
particle.curColor.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
particle.curColor.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
particle.deltaColor.r = (clamp(endColor.r + endColorVar.r * (random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
particle.deltaColor.g = (clamp(endColor.g + endColorVar.g * (random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
particle.deltaColor.b = (clamp(endColor.b + endColorVar.b * (random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
@@ -329,6 +333,14 @@ export class Simulator {
Vec4.toArray(vbuf, _col, offset + 32);
}
private _updateColor (): void {
const selfNode = this.sys.node;
const parentNode = selfNode.parent;
const uiProps = selfNode._uiProps;
const parentOpacity = parentNode ? parentNode._uiProps.opacity : 1.0;
this._parentAlpha = uiProps.localOpacity * parentOpacity;
}
public step (dt: number): void {
const assembler = this.sys.assembler as Particle2DAssembler;
const psys = this.sys;
@@ -379,6 +391,8 @@ export class Simulator {
this.updateUVs();
}
this._updateColor();
// Used to reduce memory allocation / creation within the loop
let particleIdx = 0;
while (particleIdx < particles.length) {
@@ -431,10 +445,15 @@ export class Simulator {
}
// color
particle.color.r += particle.deltaColor.r * dt;
particle.color.g += particle.deltaColor.g * dt;
particle.color.b += particle.deltaColor.b * dt;
particle.color.a += particle.deltaColor.a * dt;
particle.curColor.r += particle.deltaColor.r * dt;
particle.curColor.g += particle.deltaColor.g * dt;
particle.curColor.b += particle.deltaColor.b * dt;
particle.curColor.a += particle.deltaColor.a * dt;
particle.color.r = particle.curColor.r;
particle.color.g = particle.curColor.g;
particle.color.b = particle.curColor.b;
particle.color.a = particle.curColor.a * this._parentAlpha;
// size
particle.size += particle.deltaSize * dt;
+2 -2
View File
@@ -23,7 +23,7 @@
*/
import { ccclass, type, serializable, editable, range } from 'cc.decorator';
import { repeat } from '../core/math';
import { approxGE, approxLT, repeat } from '../core/math';
import CurveRange from './animator/curve-range';
import type { ParticleSystem } from './particle-system';
@@ -108,7 +108,7 @@ export default class Burst {
let preFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration) - dt;
preFrameTime = (preFrameTime > 0.0) ? preFrameTime : 0.0;
const curFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration);
if (this._curTime >= preFrameTime && this._curTime < curFrameTime) {
if (approxGE(this._curTime, preFrameTime) && approxLT(this._curTime, curFrameTime)) {
psys.emit(this.count.evaluate(this._curTime / psys.duration, 1), dt - (curFrameTime - this._curTime));
this._curTime += this.repeatInterval;
--this._remainingCount;
+10 -1
View File
@@ -25,7 +25,7 @@
import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable,
range, visible, override, displayName } from 'cc.decorator';
import { Material, Texture2D } from '../asset/assets';
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean } from '../core';
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean, Color } from '../core';
import { LineModel } from './models/line-model';
import { builtinResMgr } from '../asset/asset-manager';
import CurveRange from './animator/curve-range';
@@ -296,6 +296,15 @@ export class Line extends ModelRenderer {
}
}
public updateColor (): void {
if (this._color) {
if (this._models[0]) {
const lineModel = this._models[0] as LineModel;
lineModel.addLineVertexData(this._positions, this._width, this._color);
}
}
}
protected _onMaterialModified (index: number, material: Material | null): void {
super._onMaterialModified(index, material);
const matIns = this.getMaterialInstance(0);
@@ -747,6 +747,12 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable;
this._defines[INSTANCE_PARTICLE] = this._useInstance;
const matIns: MaterialInstance | null = ps.getMaterialInstance(0);
if (matIns === null || matIns === undefined) {
ps.setSharedMaterial(mat.parent, 0); // set material[0] as material for ui-mesh-renderer to use
ps.setMaterialInstance(mat, 0);
}
mat.recompileShaders(this._defines);
if (this._model) {
this._model.updateMaterial(mat);
+23 -1
View File
@@ -31,7 +31,7 @@ import { murmurhash2_32_gc, errorID, assertID, cclegacy, warnID } from '../../co
import {
BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color,
BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet,
DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, Shader, PipelineLayout, deviceManager, UniformBlock,
DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, SampleCount, Texture, Shader, PipelineLayout, deviceManager, UniformBlock,
} from '../../gfx';
import { EffectAsset } from '../../asset/assets/effect-asset';
import { IProgramInfo, programLib } from './program-lib';
@@ -139,6 +139,28 @@ export class Pass {
if (bsInfo.isA2C !== undefined) { bs.isA2C = bsInfo.isA2C; }
if (bsInfo.isIndepend !== undefined) { bs.isIndepend = bsInfo.isIndepend; }
if (bsInfo.blendColor !== undefined) { bs.blendColor = bsInfo.blendColor as Color; }
// A2C (Alpha to Coverage) requires MSAA to be effective.
// Without multiple subsamples, A2C behaves like alpha-test at ~0.5 and should be disabled.
// Disable A2C when neither the pass nor the global framebuffer has MSAA enabled:
// - passWantsMultisample: pass explicitly requests isMultisample
// - globalMsaaEnabled: swapchain has MSAA (native: colorTexture.samples > X1;
// WebGL: antialias from gl.getContextAttributes(), since WebGL
// MSAA is controlled at context level, not texture level)
if (bs.isA2C) {
const gfxDevice = deviceManager.gfxDevice as any;
const gl: WebGL2RenderingContext | WebGLRenderingContext | null = gfxDevice.gl || null;
const ctxAttrs = gl && gl.getContextAttributes();
const antialias: boolean = !!(ctxAttrs && ctxAttrs.antialias);
const passWantsMultisample = (info.rasterizerState && info.rasterizerState.isMultisample === true);
const swapchain = deviceManager.swapchain;
const colorTex = swapchain && swapchain.colorTexture;
const msaaDisabled = (!colorTex || (colorTex && colorTex.samples <= SampleCount.X1))
|| !antialias || !passWantsMultisample;
if (msaaDisabled) {
bs.isA2C = false;
}
}
}
pass._rs.assign(info.rasterizerState as RasterizerState);
pass._dss.assign(info.depthStencilState as DepthStencilState);
+11 -2
View File
@@ -21,12 +21,14 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { DEBUG } from 'internal:constants';
import { screenAdapter } from 'pal/screen-adapter';
import { Orientation } from '../../../pal/screen-adapter/enum-type';
import {
TextureType, TextureUsageBit, Format, RenderPass, Texture, Framebuffer,
RenderPassInfo, Device, TextureInfo, FramebufferInfo, Swapchain, SurfaceTransform, TextureFlagBit, TextureFlags,
} from '../../gfx';
import { warn } from '../../core/platform/debug';
import { Root } from '../../root';
import { Camera } from '../scene';
@@ -41,7 +43,10 @@ export interface IRenderWindowInfo {
externalFlag?: TextureFlags; // external texture type normal or oes
}
const orientationMap: Record<Orientation, SurfaceTransform> = {
// NOTE: `Orientation` is a flag enum whose composite members (LANDSCAPE, AUTO) are never
// actual runtime orientations, so this map intentionally only covers the physical ones.
// It is therefore typed as Partial rather than a total Record<Orientation, ...>.
const orientationMap: Partial<Record<Orientation, SurfaceTransform>> = {
[Orientation.PORTRAIT]: SurfaceTransform.IDENTITY,
[Orientation.LANDSCAPE_RIGHT]: SurfaceTransform.ROTATE_90,
[Orientation.PORTRAIT_UPSIDE_DOWN]: SurfaceTransform.ROTATE_180,
@@ -253,7 +258,11 @@ export class RenderWindow {
*/
public resize (width: number, height: number): void {
if (this._swapchain) {
this._swapchain.resize(width, height, orientationMap[screenAdapter.orientation]);
const surfaceTransform = orientationMap[screenAdapter.orientation];
if (DEBUG && surfaceTransform === undefined) {
warn(`Unexpected screen orientation: ${screenAdapter.orientation}`);
}
this._swapchain.resize(width, height, surfaceTransform || SurfaceTransform.IDENTITY);
this._width = this._swapchain.width;
this._height = this._swapchain.height;
} else {
+3
View File
@@ -91,6 +91,9 @@ export class PointLight extends Light {
* @en The luminance of the light source in LDR mode.
* @zh LDR 模式下光源的亮度。
*/
get luminanceLDR (): number {
return this._luminanceLDR;
}
set luminanceLDR (value: number) {
this._luminanceLDR = value;
}
+71 -39
View File
@@ -67,11 +67,13 @@ export class ReflectionProbe {
protected readonly _size = v3(1, 1, 1);
/**
* @en Render cubemap's camera
* @zh 渲染cubemap的相机
* @en Camera used for probe rendering (cubemap capture or planar reflection).
* @zh 用于探针渲染的相机(cubemap 采集或平面反射)
*/
private _camera: Camera | null = null;
private _previewCamera: Camera | null = null;
/**
* @en Unique id of probe.
* @zh probe的唯一id
@@ -184,6 +186,9 @@ export class ReflectionProbe {
set visibility (val) {
this._visibility = val;
this._camera!.visibility = this._visibility;
if (this._previewCamera) {
this._previewCamera.visibility = this._visibility;
}
}
/**
@@ -320,6 +325,21 @@ export class ReflectionProbe {
this._needRender = true;
}
/**
* @engineInternal
* @mangle
*/
public renderPreviewPlanarReflection (sourceCamera: Camera): Camera {
if (!this._previewCamera) {
this._createCamera(new Node(`${this.cameraNode.name} Preview Reflection`), true);
}
const previewCamera = this._previewCamera!;
this._syncCameraParams(sourceCamera, previewCamera);
this._transformReflectionCamera(sourceCamera, previewCamera);
this._needRender = true;
return previewCamera;
}
public switchProbeType (type: ProbeType, sourceCamera: Camera | null): void {
if (type === ProbeType.CUBE) {
this._needRender = false;
@@ -357,6 +377,12 @@ export class ReflectionProbe {
this._camera.destroy();
this._camera = null;
}
if (this._previewCamera) {
const cameraNode = this._previewCamera.node;
this._previewCamera.destroy();
this._previewCamera = null;
cameraNode.destroy();
}
for (let i = 0; i < this.bakedCubeTextures.length; i++) {
this.bakedCubeTextures[i].destroy();
}
@@ -410,48 +436,54 @@ export class ReflectionProbe {
return true;
}
private _syncCameraParams (camera: Camera): void {
this.camera.projectionType = camera.projectionType;
this.camera.orthoHeight = camera.orthoHeight;
this.camera.nearClip = camera.nearClip;
this.camera.farClip = camera.farClip;
this.camera.fov = camera.fov;
this.camera.clearFlag = camera.clearFlag;
this.camera.clearColor = camera.clearColor;
this.camera.priority = camera.priority - 1;
this.camera.resize(camera.width, camera.height);
private _syncCameraParams (camera: Camera, targetCamera: Camera = this.camera): void {
targetCamera.projectionType = camera.projectionType;
targetCamera.orthoHeight = camera.orthoHeight;
targetCamera.nearClip = camera.nearClip;
targetCamera.farClip = camera.farClip;
targetCamera.fov = camera.fov;
targetCamera.clearFlag = camera.clearFlag;
targetCamera.clearColor = camera.clearColor;
targetCamera.priority = camera.priority - 1;
targetCamera.resize(camera.width, camera.height);
}
private _createCamera (cameraNode: Node): Camera | null {
private _createCamera (cameraNode: Node, preview = false): Camera | null {
const root = cclegacy.director.root;
if (!this._camera) {
this._camera = root.createCamera();
if (!this._camera) return null;
this._camera.initialize({
let camera = preview ? this._previewCamera : this._camera;
if (!camera) {
camera = root.createCamera();
if (!camera) return null;
camera.initialize({
name: cameraNode.name,
node: cameraNode,
projection: CameraProjection.PERSPECTIVE,
window: EDITOR ? root && root.mainWindow : root && root.tempWindow,
window: preview || EDITOR ? root.mainWindow : root.tempWindow,
priority: 0,
cameraType: CameraType.DEFAULT,
trackingType: TrackingType.NO_TRACKING,
});
if (preview) {
this._previewCamera = camera;
} else {
this._camera = camera;
}
}
this._camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
this._camera.fovAxis = CameraFOVAxis.VERTICAL;
this._camera.fov = toRadian(90);
this._camera.orthoHeight = 10;
this._camera.nearClip = 1;
this._camera.farClip = 1000;
this._camera.clearColor = this._backgroundColor;
this._camera.clearDepth = 1.0;
this._camera.clearStencil = 0.0;
this._camera.clearFlag = this._clearFlag;
this._camera.visibility = this._visibility;
this._camera.aperture = CameraAperture.F16_0;
this._camera.shutter = CameraShutter.D125;
this._camera.iso = CameraISO.ISO100;
return this._camera;
camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
camera.fovAxis = CameraFOVAxis.VERTICAL;
camera.fov = toRadian(90);
camera.orthoHeight = 10;
camera.nearClip = 1;
camera.farClip = 1000;
camera.clearColor = this._backgroundColor;
camera.clearDepth = 1.0;
camera.clearStencil = 0.0;
camera.clearFlag = this._clearFlag;
camera.visibility = this._visibility;
camera.aperture = CameraAperture.F16_0;
camera.shutter = CameraShutter.D125;
camera.iso = CameraISO.ISO100;
return camera;
}
private _resetCameraParams (): void {
@@ -478,10 +510,10 @@ export class ReflectionProbe {
return rt;
}
private _transformReflectionCamera (sourceCamera: Camera): void {
private _transformReflectionCamera (sourceCamera: Camera, targetCamera: Camera = this.camera): void {
const offset = Vec3.dot(this.node.worldPosition, this.node.up);
this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset);
this.cameraNode.worldPosition = this._cameraWorldPos;
targetCamera.node.worldPosition = this._cameraWorldPos;
Vec3.transformQuat(this._forward, Vec3.FORWARD, sourceCamera.node.worldRotation);
this._reflect(this._forward, this._forward, this.node.up, 0);
@@ -494,14 +526,14 @@ export class ReflectionProbe {
Quat.fromViewUp(this._cameraWorldRotation, this._forward, this._up);
this.cameraNode.worldRotation = this._cameraWorldRotation;
targetCamera.node.worldRotation = this._cameraWorldRotation;
this.camera.update(true);
targetCamera.update(true);
// Transform the plane from world space to reflection camera space use the inverse transpose matrix
const viewSpaceProbe = new Vec4(this.node.up.x, this.node.up.y, this.node.up.z, -Vec3.dot(this.node.up, this.node.worldPosition));
viewSpaceProbe.transformMat4(this.camera.matView.clone().invert().transpose());
this.camera.calculateObliqueMat(viewSpaceProbe);
viewSpaceProbe.transformMat4(targetCamera.matView.clone().invert().transpose());
targetCamera.calculateObliqueMat(viewSpaceProbe);
}
private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 {
+3
View File
@@ -102,6 +102,9 @@ export class SphereLight extends Light {
* @en The luminance of the light source in LDR mode
* @zh LDR 模式下光源的亮度
*/
get luminanceLDR (): number {
return this._luminanceLDR;
}
set luminanceLDR (value: number) {
this._luminanceLDR = value;
}
-2
View File
@@ -22,7 +22,6 @@
THE SOFTWARE.
****************************************************************************/
import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx';
import { genHashValue } from './define';
import { VectorGraphColorMap } from './effect';
import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph';
import { LayoutGraphData } from './layout-graph';
@@ -199,7 +198,6 @@ class PassVisitor implements RenderGraphVisitor {
resourceGraph.visitVertex(this._resVisitor, vertID);
}
}
genHashValue(pass);
}
}
applyID (id: number, resId: number): void {
+22 -2
View File
@@ -195,10 +195,13 @@ function sceneCulling (
}
models.push(model);
} else if (probe.probeType === ProbeType.CUBE) {
if (!wBounds || !model.bakeToReflectionProbe) {
continue;
}
if (!isVisible(model, visibility)) {
continue;
}
if (wBounds && isIntersectAABB(wBounds, probe.boundingBox!)) {
if (isIntersectAABB(wBounds, probe.boundingBox!)) {
continue;
}
models.push(model);
@@ -475,7 +478,8 @@ export class SceneCulling {
);
// Get or create render queue
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, sceneData.camera);
const renderCamera = sceneData.light.probe ? sceneData.light.probe.camera : sceneData.camera;
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, renderCamera);
// add render queue query
const renderQueueQuery = this.cullingPools.renderQueueQueryRecycle.add();
@@ -556,7 +560,11 @@ export class SceneCulling {
private executeSphereLightCulling (light: SphereLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(modelBounds, lightAABB)) {
lightBoundsCullingResult.push(model);
@@ -567,7 +575,11 @@ export class SceneCulling {
private executeSpotLightCulling (light: SpotLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const lightFrustum: Frustum = light.frustum;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || (intersect.aabbWithAABB(lightAABB, modelBounds) && intersect.aabbFrustum(modelBounds, lightFrustum))) {
lightBoundsCullingResult.push(model);
@@ -577,7 +589,11 @@ export class SceneCulling {
private executePointLightCulling (light: PointLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
@@ -590,8 +606,12 @@ export class SceneCulling {
frustumCullingResult: Array<Model>,
lightBoundsCullingResult: Array<Model>,
): void {
const visibility = light.visibility;
rangedDirLightBoundingBox.transform(light.node!.worldMatrix, null, null, null, lightAABB);
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
+23 -7
View File
@@ -258,9 +258,19 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void {
const lightTarget = light.light;
this.addScene(camera, sceneFlags, lightTarget);
const scene = light.probe?.node?.scene?.renderScene || undefined;
this._addScene(camera, sceneFlags, lightTarget, scene, light);
}
addScene (camera: Camera, sceneFlags = SceneFlags.NONE, light: Light | undefined | null = null, scene: RenderScene | undefined = undefined): SceneBuilder {
return this._addScene(camera, sceneFlags, light, scene);
}
private _addScene (
camera: Camera,
sceneFlags: SceneFlags,
light: Light | undefined | null,
scene: RenderScene | undefined,
lightInfo: LightInfo | null = null,
): SceneBuilder {
const sceneData = renderGraphPool.createSceneData(
scene || camera.scene,
camera,
@@ -268,6 +278,9 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
light && !(sceneFlags & SceneFlags.SHADOW_CASTER) ? CullingFlags.CAMERA_FRUSTUM | CullingFlags.LIGHT_BOUNDS : CullingFlags.CAMERA_FRUSTUM,
light,
);
if (lightInfo) {
sceneData.light.reset(lightInfo.light, lightInfo.level, lightInfo.culledByLight, lightInfo.probe);
}
const renderData = renderGraphPool.createRenderData();
const sceneId = this._renderGraph.addVertex<RenderGraphValue.Scene>(RenderGraphValue.Scene, sceneData, 'Scene', '', renderData, !DEBUG, this._vertID);
if (!(sceneFlags & SceneFlags.NON_BUILTIN)) {
@@ -1650,13 +1663,16 @@ export class WebPipeline extends WebSetter implements BasicPipeline {
this._compiler = new Compiler(this, this._renderGraph, this._resourceGraph, this._lg);
}
this._compiler.compile(this._renderGraph);
} else {
this._renderGraph.x.forEach((vert) => {
if (vert.t === RenderGraphValue.RasterPass) {
genHashValue(vert.j as RasterPass);
}
});
}
this._renderGraph.x.forEach((vert, v) => {
if (vert.t !== RenderGraphValue.RasterPass) {
return;
}
if (DEBUG && !this._renderGraph!.getValid(v)) {
return;
}
genHashValue(vert.j as RasterPass);
});
}
execute (): void {
+88 -48
View File
@@ -28,8 +28,9 @@ import { UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMA
UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, ENABLE_PROBE_BLEND,
IRenderPass,
getPassPool } from './define';
import { BufferUsageBit, MemoryUsageBit, Device, Texture, InputAssembler, InputAssemblerInfo,
import { BufferUsageBit, MemoryUsageBit, Device, InputAssembler, InputAssemblerInfo,
Attribute, Buffer, BufferInfo, CommandBuffer, Shader, DescriptorSet } from '../gfx';
import type { Texture } from '../gfx';
import { RecyclePool } from '../core/memop';
export function instancingCompareFn (l: InstancedBuffer, r: InstancedBuffer): number {
@@ -65,6 +66,7 @@ export class InstancedBuffer {
public sortRender: IRenderPass;
private declare _passPool: RecyclePool<IRenderPass>;
private declare _device: Device;
private readonly _instanceMap = new Map<string, IInstancedItem[]>();
constructor (pass: Pass) {
this._device = pass.device;
this.pass = pass;
@@ -81,6 +83,7 @@ export class InstancedBuffer {
});
this._passPool.reset();
this.instances.length = 0;
this._instanceMap.clear();
}
public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null): void {
@@ -106,72 +109,109 @@ export class InstancedBuffer {
this.sortRender.hash = hash;
this.sortRender.shaderId = shader.typedID;
this.sortRender.passIdx = passIdx;
for (let i = 0; i < this.instances.length; ++i) {
const instance = this.instances[i];
if (instance.ia.indexBuffer?.objectID !== sourceIA.indexBuffer?.objectID || instance.count >= MAX_CAPACITY) { continue; }
// check same binding
if (instance.lightingMap.objectID !== lightingMap.objectID) {
continue;
const key = `${sourceIA.indexBuffer?.objectID ?? 0}/${lightingMap.objectID}/${useReflectionProbeType}/`
+ `${reflectionProbeCubemap.objectID}/${reflectionProbePlanarMap.objectID}/`
+ `${ENABLE_PROBE_BLEND ? reflectionProbeBlendCubemap!.objectID : 0}/${stride}`;
const mappedInstances = this._instanceMap.get(key);
if (mappedInstances) {
for (let i = 0; i < mappedInstances.length; ++i) {
const instance = mappedInstances[i];
if (instance.count >= MAX_CAPACITY) { continue; }
this._appendInstance(instance, attrs.buffer, shader, descriptorSet);
return;
}
if (instance.useReflectionProbeType !== useReflectionProbeType) {
continue;
}
if (instance.reflectionProbeCubemap.objectID !== reflectionProbeCubemap.objectID) {
continue;
}
if (instance.reflectionProbePlanarMap.objectID !== reflectionProbePlanarMap.objectID) {
continue;
}
if (ENABLE_PROBE_BLEND && instance.reflectionProbeBlendCubemap!.objectID !== reflectionProbeBlendCubemap!.objectID) {
continue;
}
if (instance.stride !== stride) {
// we allow this considering both baked and non-baked
// skinning models may be present in the same buffer
continue;
}
if (instance.count >= instance.capacity) { // resize buffers
instance.capacity <<= 1;
const newSize = instance.stride * instance.capacity;
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData);
instance.vb.resize(newSize);
}
instance.shader = shader;
instance.descriptorSet = descriptorSet;
instance.data.set(attrs.buffer, instance.stride * instance.count++);
this.hasPendingModels = true;
return;
}
// Create a new instance
this._createInstance(
key,
sourceIA,
attrs.attributes,
attrs.buffer,
stride,
shader,
descriptorSet,
lightingMap,
useReflectionProbeType,
reflectionProbeCubemap,
reflectionProbePlanarMap,
reflectionProbeBlendCubemap,
);
}
private _appendInstance (instance: IInstancedItem, data: Uint8Array, shader: Shader, descriptorSet: DescriptorSet): void {
if (instance.count >= instance.capacity) { // resize buffers
instance.capacity = Math.min(instance.capacity << 1, MAX_CAPACITY);
const newSize = instance.stride * instance.capacity;
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData);
instance.vb.resize(newSize);
}
instance.shader = shader;
instance.descriptorSet = descriptorSet;
instance.data.set(data, instance.stride * instance.count++);
this.hasPendingModels = true;
}
private _createInstance (
key: string,
sourceIA: InputAssembler,
instancedAttributes: Attribute[],
instanceData: Uint8Array,
stride: number,
shader: Shader,
descriptorSet: DescriptorSet,
lightingMap: Texture,
useReflectionProbeType: number,
reflectionProbeCubemap: Texture,
reflectionProbePlanarMap: Texture,
reflectionProbeBlendCubemap: Texture | null,
): void {
const newSize = stride * INITIAL_CAPACITY;
const vb = this._device.createBuffer(new BufferInfo(
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
stride * INITIAL_CAPACITY,
newSize,
stride,
));
const data = new Uint8Array(stride * INITIAL_CAPACITY);
const data = new Uint8Array(newSize);
const vertexBuffers = sourceIA.vertexBuffers.slice();
const attributes = sourceIA.attributes.slice();
const indexBuffer = sourceIA.indexBuffer;
for (let i = 0; i < attrs.attributes.length; i++) {
const attr = attrs.attributes[i];
for (let i = 0; i < instancedAttributes.length; i++) {
const attr = instancedAttributes[i];
const newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
attributes.push(newAttr);
}
data.set(attrs.buffer);
data.set(instanceData);
vertexBuffers.push(vb);
const iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
const ia = this._device.createInputAssembler(iaInfo);
// eslint-disable-next-line max-len
this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, lightingMap, reflectionProbeCubemap, reflectionProbePlanarMap, useReflectionProbeType, reflectionProbeBlendCubemap });
const instance = {
count: 1,
capacity: INITIAL_CAPACITY,
vb,
data,
ia,
stride,
shader,
descriptorSet,
lightingMap,
reflectionProbeCubemap,
reflectionProbePlanarMap,
useReflectionProbeType,
reflectionProbeBlendCubemap,
} as IInstancedItem;
this.instances.push(instance);
let mappedInstances = this._instanceMap.get(key);
if (!mappedInstances) {
mappedInstances = [];
this._instanceMap.set(key, mappedInstances);
}
mappedInstances.push(instance);
this.hasPendingModels = true;
}
@@ -180,7 +220,7 @@ export class InstancedBuffer {
const instance = this.instances[i];
if (!instance.count) { continue; }
instance.ia.instanceCount = instance.count;
cmdBuff.updateBuffer(instance.vb, instance.data);
cmdBuff.updateBuffer(instance.vb, instance.data.buffer as ArrayBuffer, instance.count * instance.stride);
}
}
+2 -5
View File
@@ -29,7 +29,6 @@ import { PipelineStateManager } from './pipeline-state-manager';
import { Model, Camera, SubModel } from '../render-scene/scene';
import { RenderInstancedQueue } from './render-instanced-queue';
import { ShadowType } from '../render-scene/scene/shadows';
import { Layers } from '../scene-graph/layers';
import { PipelineRuntime } from './custom/pipeline';
import { BatchingSchemes, Pass } from '../render-scene/core/pass';
import { getPhaseID } from './pass-phase';
@@ -83,18 +82,16 @@ export class PlanarShadowQueue {
const scene = camera.scene!;
const frustum = camera.frustum;
const shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 0;
const shadowVisible = camera.visibility !== 0;
if (!scene.mainLight || !shadowVisible) { return; }
const models = scene.models;
const visibility = camera.visibility;
for (let i = 0; i < models.length; i++) {
const model = models[i];
if (scene.isCulledByLod(camera, model)) {
continue;
}
if (model.enabled && model.node && model.castShadow
&& (model.node && ((visibility & model.node.layer) === model.node.layer))) {
if (model.enabled && model.node && model.castShadow) {
this._castModels.push(model);
}
}
@@ -27,7 +27,7 @@ import { IRenderFlowInfo, RenderFlow } from '../render-flow';
import { ReflectionProbeStage } from './reflection-probe-stage';
import { RenderFlowTag } from '../pipeline-serialization';
import { RenderPipeline } from '../render-pipeline';
import { Camera } from '../../render-scene/scene/camera';
import { Camera, CameraUsage } from '../../render-scene/scene/camera';
import { ProbeType, ReflectionProbe } from '../../render-scene/scene/reflection-probe';
import { cclegacy } from '../../core';
@@ -65,7 +65,13 @@ export class ReflectionProbeFlow extends RenderFlow {
const probes = cclegacy.internal.reflectionProbeManager.getProbes() as ReflectionProbe[];
for (let i = 0; i < probes.length; i++) {
if (probes[i].needRender) {
if (EDITOR || probes[i].probeType === ProbeType.PLANAR) {
if (probes[i].probeType === ProbeType.PLANAR) {
let reflectionCamera: Camera | undefined;
if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) {
reflectionCamera = probes[i].renderPreviewPlanarReflection(camera);
}
this._renderStage(camera, probes[i], reflectionCamera);
} else if (EDITOR) {
this._renderStage(camera, probes[i]);
}
}
@@ -75,12 +81,12 @@ export class ReflectionProbeFlow extends RenderFlow {
public destroy (): void {
super.destroy();
}
private _renderStage (camera: Camera, probe: ReflectionProbe): void {
private _renderStage (camera: Camera, probe: ReflectionProbe, reflectionCamera?: Camera): void {
for (let i = 0; i < this._stages.length; i++) {
const probeStage = this._stages[i] as ReflectionProbeStage;
if (probe.probeType === ProbeType.PLANAR) {
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, null);
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer);
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer, reflectionCamera);
probeStage.render(camera);
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, probe.realtimePlanarTexture!.getGFXTexture());
} else {
@@ -55,6 +55,7 @@ export class ReflectionProbeStage extends RenderStage {
private _frameBuffer: Framebuffer | null = null;
private _renderArea = new Rect();
private _probe: ReflectionProbe | null = null;
private _reflectionCamera: Camera | null = null;
private _probeRenderQueue!: RenderReflectionProbeQueue;
private _rgbeColor = new Vec3();
@@ -68,9 +69,10 @@ export class ReflectionProbeStage extends RenderStage {
* @param probe
* @param frameBuffer
*/
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer): void {
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer, reflectionCamera?: Camera): void {
this._probe = probe;
this._frameBuffer = frameBuffer;
this._reflectionCamera = reflectionCamera ?? null;
}
public destroy (): void {
@@ -108,8 +110,9 @@ export class ReflectionProbeStage extends RenderStage {
public render (camera: Camera): void {
const pipeline = this._pipeline;
const cmdBuff = pipeline.commandBuffers[0];
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff);
pipeline.pipelineUBO.updateCameraUBO(this._probe!.camera);
const probeCamera = this._reflectionCamera ?? this._probe!.camera;
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff, probeCamera);
pipeline.pipelineUBO.updateCameraUBO(probeCamera);
this._renderArea.x = 0;
this._renderArea.y = 0;
@@ -118,10 +121,10 @@ export class ReflectionProbeStage extends RenderStage {
const renderPass = this._frameBuffer!.renderPass;
if (this._probe!.camera.clearFlag & ClearFlagBit.COLOR) {
this._rgbeColor.x = this._probe!.camera.clearColor.x;
this._rgbeColor.y = this._probe!.camera.clearColor.y;
this._rgbeColor.z = this._probe!.camera.clearColor.z;
if (probeCamera.clearFlag & ClearFlagBit.COLOR) {
this._rgbeColor.x = probeCamera.clearColor.x;
this._rgbeColor.y = probeCamera.clearColor.y;
this._rgbeColor.z = probeCamera.clearColor.z;
const rgbe = packRGBE(this._rgbeColor);
colors[0].x = rgbe.x;
colors[0].y = rgbe.y;
@@ -134,8 +137,8 @@ export class ReflectionProbeStage extends RenderStage {
this._frameBuffer!,
this._renderArea,
colors,
this._probe!.camera.clearDepth,
this._probe!.camera.clearStencil,
probeCamera.clearDepth,
probeCamera.clearStencil,
);
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
@@ -320,7 +320,8 @@ export class RenderAdditiveLightQueue {
const lightIdx = _lightIndices[l];
const light = validPunctualLights[lightIdx];
const visibility = light.visibility;
if (((visibility & model.node.layer) === model.node.layer)) {
if (((visibility & model.node.layer) === model.node.layer)
|| (visibility & model.visFlags)) {
switch (batchingScheme) {
case BatchingSchemes.INSTANCING: {
const buffer = pass.getInstancedBuffer(lightIdx);
@@ -79,13 +79,14 @@ export class RenderReflectionProbeQueue {
public constructor (pipeline: PipelineRuntime) {
this._pipeline = pipeline;
}
public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer): void {
public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer, reflectionCamera?: Camera): void {
this.clear();
const scene = camera.scene!;
const sceneData = this._pipeline.pipelineSceneData;
const skybox = sceneData.skybox;
const probeCamera = reflectionCamera ?? probe.camera;
if (skybox.enabled && skybox.model && (probe.camera.clearFlag & SkyBoxFlagValue.VALUE)) {
if (skybox.enabled && skybox.model && (probeCamera.clearFlag & SkyBoxFlagValue.VALUE)) {
this.add(skybox.model);
}
@@ -105,7 +106,7 @@ export class RenderReflectionProbeQueue {
if (geometry.intersect.aabbWithAABB(model.worldBounds, probe.boundingBox!)) {
this.add(model);
}
} else if (geometry.intersect.aabbFrustum(model.worldBounds, probe.camera.frustum)) {
} else if (geometry.intersect.aabbFrustum(model.worldBounds, probeCamera.frustum)) {
this.add(model);
}
}
+2 -2
View File
@@ -195,8 +195,8 @@ export function sceneCulling (sceneData: PipelineSceneData, pipelineUBO: Pipelin
csmLayerObjects.push(getRenderObject(model, camera));
}
if (model.node && ((visibility & model.node.layer) === model.node.layer)
|| (visibility & model.visFlags)) {
if ((model.node && ((visibility & model.node.layer) === model.node.layer))
|| (visibility & model.visFlags)) {
// frustum culling
if (model.worldBounds && !geometry.intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
return;
+13 -9
View File
@@ -27,7 +27,7 @@ import { Material, Texture2D } from '../asset/assets';
import { error, errorID, logID, warnID } from '../core/platform/debug';
import { Enum, EnumType, ccenum } from '../core/value-types/enum';
import { Node, NodeEventType } from '../scene-graph';
import { CCObjectFlags, Color, RecyclePool, js } from '../core';
import { CCObjectFlags, Color, RecyclePool, js, math } from '../core';
import { SkeletonData } from './skeleton-data';
import type { Graphics } from '../2d/components/graphics';
import { UIRenderer } from '../2d/framework/ui-renderer';
@@ -850,14 +850,12 @@ export class Skeleton extends UIRenderer {
warnID(16410);
}
const skeletonInfo = this._skeletonCache!.getSkeletonInfo(this._skeletonData!);
if (this._skeletonInfo !== skeletonInfo) {
if (this._skeletonInfo !== skeletonInfo || (!this._skeletonInfo && !skeletonInfo)) {
this._destroySkeletonInfo(this._skeletonCache);
if (!skeletonInfo && this._cacheMode === SpineAnimationCacheMode.PRIVATE_CACHE) {
this._animCache = this._skeletonCache!.initAnimationCache(this.skeletonData!.uuid, this._skeletonData!, this._animationName);
}
this._skeletonInfo = this._skeletonCache!.createSkeletonInfo(this._skeletonData!);
}
if (this._skeletonInfo) {
this._skeleton = this._skeletonInfo.skeleton!;
}
} else {
@@ -1589,7 +1587,7 @@ export class Skeleton extends UIRenderer {
const socket = this._sockets[i];
if (socket.path && socket.target) {
const boneIdx = this._cachedSockets.get(socket.path);
if (!boneIdx) {
if (boneIdx == null || boneIdx < 0) {
error(`Skeleton data does not contain path ${socket.path}`);
continue;
}
@@ -1883,10 +1881,16 @@ export class Skeleton extends UIRenderer {
*/
public setTrackCompleteListener (entry: spine.TrackEntry, listener: TrackListener2): void {
const onComplete = (trackEntry: spine.TrackEntry): void => {
const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
listener(trackEntry, loopCount);
// this._instance.setListener(listenerID, spine.EventType.event);
// this._listener!.event = listener;
const animEnd = math.equals(trackEntry.animationEnd, -1.0) ? trackEntry.animation.duration : trackEntry.animationEnd;
const duration = animEnd - trackEntry.animationStart;
if (duration > 0) {
const loopCount = trackEntry.loop ? Math.floor(trackEntry.trackTime / duration) : 1;
listener(trackEntry, loopCount);
// this._instance.setListener(listenerID, spine.EventType.event);
// this._listener!.event = listener;
} else {
warnID(16420);
}
};
TrackEntryListeners.getListeners(entry, this._instance!).complete = onComplete;
}
+1 -1
View File
@@ -204,7 +204,7 @@ function align (node: Node, widget: Widget): void {
// TODO: type is hack, Change to the type actually used (Node or BaseNode) when BaseNode complete
function visitNode (node: any): void {
const widget = node.getComponent(Widget);
if (widget && widget.enabled) {
if (widget && widget.enabled && cclegacy.isValid(widget, true)) {
if (DEV) {
widget._validateTargetInDEV();
}
+3
View File
@@ -852,6 +852,9 @@ export class Widget extends Component {
}
public onDestroy (): void {
// `onDisable` is skipped when the component was never enabled by the scheduler
// (`IsOnEnableCalled` unset), so unregister here as well.
cclegacy._widgetManager?.remove(this);
this._removeParentEvent();
}
@@ -81,9 +81,10 @@ vec3 CalculateNormal(vec3 tangent, vec3 binormal)
// return value is un-normalized
vec3 CalculateNormalFromTangentSpace(vec3 normalFromTangentSpace, float normalStrength, vec3 normal, vec3 tangent, float mirrorNormal)
{
// according to the linearly interpolated mirrorNormal value, the binormal length should vary linearly to ensure geometric smoothness. therefore, explicit normalization is unnecessary.
vec3 binormal = CalculateBinormal(normal, tangent, mirrorNormal);
return (normalFromTangentSpace.x * normalStrength) * normalize(tangent) +
(normalFromTangentSpace.y * normalStrength) * normalize(binormal) +
(normalFromTangentSpace.y * normalStrength) * binormal +
normalFromTangentSpace.z * normalize(normal);
}
@@ -222,7 +222,9 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
vec3 R = normalize(reflect(-V, N));
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
if(s.reflectionProbeId < 0.0){
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#if CC_USE_IBL
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -247,7 +249,9 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
env = unpackRGBE(probe);
#elif CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND || CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
if (s.reflectionProbeId < 0.0) {
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#if CC_USE_IBL
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#endif
} else {
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -256,7 +260,10 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
env = SampleReflectionProbe(cc_reflectionProbeCubemap, fixedR.xyz, s.roughness, mipCount, isReflectProbeUsingRGBE(s.reflectionProbeId));
if (s.reflectionProbeBlendId < 0.0) {
vec3 skyBoxEnv = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE) * lightIntensity;
vec3 skyBoxEnv = vec3(0.0);
#if CC_USE_IBL
skyBoxEnv = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE) * lightIntensity;
#endif
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
//blend with skybox
env = mix(env, skyBoxEnv, s.reflectionProbeBlendFactor);
@@ -99,7 +99,10 @@ vec3 SampleEnvironmentSpecular(samplerCube tex, in LightingIntermediateData ligh
vec4 fixedR = CalculateBoxProjectedDirection(R, worldPos, cubeCenterPos, boxHalfSize);
R = fixedR.xyz;
vec3 envmap = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).xyz * cc_ambientSky.w;
vec3 envmap = vec3(0.0);
#if CC_USE_IBL
envmap = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).xyz * cc_ambientSky.w;
#endif
#if CC_SURFACES_LIGHTING_ANISOTROPIC && CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT
envSpec = EnvAnisotropicReflection(tex, fixedR.xyz, roughness, mipCount, lightingData.anisotropyShape, lightingData.V, lightingData.N, lightingData.T, lightingData.B);
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
@@ -159,7 +162,9 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
if(FSInput_reflectionProbeId < 0.0){
#if CC_USE_IBL
envSpec = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -181,7 +186,9 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
}
#elif CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND || CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
if(FSInput_reflectionProbeId < 0.0){
#if CC_USE_IBL
envSpec = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -197,7 +204,10 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
if(FSInput_reflectionProbeBlendId < 0.0)
{
vec3 skyBoxEnv = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).rgb * lightIntensity;
vec3 skyBoxEnv = vec3(0.0);
#if CC_USE_IBL
skyBoxEnv = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).rgb * lightIntensity;
#endif
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
//blend with skybox
envSpec = mix(envSpec, skyBoxEnv, blendFactor);
@@ -434,7 +434,8 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// Reflection Probe
cameraConfigs.enablePlanarReflectionProbe = cameraConfigs.isMainGameWindow
|| camera.cameraUsage === CameraUsage.SCENE_VIEW
|| camera.cameraUsage === CameraUsage.GAME_VIEW;
|| camera.cameraUsage === CameraUsage.GAME_VIEW
|| camera.cameraUsage === CameraUsage.PREVIEW;
// MSAA
cameraConfigs.enableMSAA = cameraConfigs.settings.msaa.enabled
@@ -551,7 +552,7 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
ppl, camera, pplConfigs.mobileMaxSpotLightShadowMaps);
}
this._tryAddReflectionProbePasses(ppl, cameraConfigs, id, mainLight, camera.scene);
this._tryAddReflectionProbePasses(ppl, cameraConfigs, id, mainLight, camera.scene, camera);
if (cameraConfigs.remainingPasses > 0 || cameraConfigs.enableShadingScale) {
context.colorName = cameraConfigs.enableShadingScale
@@ -630,6 +631,7 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
id: number,
mainLight: renderer.scene.DirectionalLight | null,
scene: renderer.RenderScene | null,
sourceCamera: renderer.scene.Camera,
): void {
const reflectionProbeManager = cclegacy.internal.reflectionProbeManager as ReflectionProbeManager | undefined;
if (!reflectionProbeManager) {
@@ -651,6 +653,10 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
if (!cameraConfigs.enablePlanarReflectionProbe) {
continue;
}
let reflectionCamera = probe.camera;
if (EDITOR && sourceCamera.cameraUsage === CameraUsage.PREVIEW) {
reflectionCamera = probe.renderPreviewPlanarReflection(sourceCamera);
}
const window: renderer.RenderWindow = probe.realtimePlanarTexture!.window!;
const colorName = `PlanarProbeRT${probeID}`;
const depthStencilName = `PlanarProbeDS${probeID}`;
@@ -663,8 +669,8 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// Rendering
const probePass = ppl.addRenderPass(width, height, 'default');
probePass.name = `PlanarReflectionProbe${probeID}`;
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera,
colorName, depthStencilName, mainLight, scene);
this._buildReflectionProbePass(probePass, cameraConfigs, id, reflectionCamera, probe,
colorName, depthStencilName, mainLight);
} else if (EDITOR) {
for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) {
probe.updateCameraDir(faceIdx);
@@ -680,8 +686,8 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// Rendering
const probePass = ppl.addRenderPass(width, height, 'default');
probePass.name = `CubeProbe${probeID}${faceIdx}`;
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera,
colorName, depthStencilName, mainLight, scene);
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera, probe,
colorName, depthStencilName, mainLight);
}
probe.needRender = false;
}
@@ -696,10 +702,10 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
cameraConfigs: Readonly<CameraConfigs & ForwardPassConfigs>,
id: number,
camera: renderer.scene.Camera,
probe: renderer.scene.ReflectionProbe,
colorName: string,
depthStencilName: string,
mainLight: renderer.scene.DirectionalLight | null,
scene: renderer.RenderScene | null = null,
): void {
const QueueHint = rendering.QueueHint;
const SceneFlags = rendering.SceneFlags;
@@ -743,11 +749,11 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// TODO(zhouzhenglong): Separate OPAQUE and MASK queue
// add opaque and mask queue
const lightInfo = new rendering.LightInfo(mainLight || null, 0, false, probe);
pass.addQueue(QueueHint.NONE, 'reflect-map') // Currently we put OPAQUE and MASK into one queue, so QueueHint is NONE
.addScene(camera,
SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.REFLECTION_PROBE,
mainLight || undefined,
scene ? scene : undefined);
.addSceneOfCamera(camera,
lightInfo,
SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.REFLECTION_PROBE);
}
private _addForwardRadiancePasses(
ppl: rendering.BasicPipeline,
+1 -1
View File
@@ -298,7 +298,7 @@ module.exports = link(mixin({
illuminance: 'Illuminance of the light',
luminous_power: 'Luminous power of the light',
luminance: 'Luminance of the light',
visibility: 'Visibility mask, declaring a set of node layers that will be visible to this valid punctual Light(Does not work with directional light)',
visibility: 'Visibility mask, declaring a set of node layers that will be visible in the current light source',
term: 'The photometric term currently being used',
size: 'Size of the light',
range: 'Range of the light',
+1 -1
View File
@@ -288,7 +288,7 @@ module.exports = link(mixin({
illuminance: '光源强度',
luminous_flux: '光通量',
luminance: '光亮度',
visibility: '可见性掩码,声明在当前精确光源中可见的节点层级集合(对方向光不生效)',
visibility: '可见性掩码,声明在当前光源中可见的节点层级集合',
term: '当前使用的光度学计量单位',
size: '光源大小',
range: '光源范围',
+7
View File
@@ -1,5 +1,12 @@
# ignore third_party code from clang-format checks
./cocos/bindings/auto/*
./cocos/base/std/**
./cocos/cocos-version.h
./cocos/editor-support/spine-wasm/**
./cocos/editor-support/spine/**
./cocos/gi/light-probe/predicates.cpp
./cocos/gi/light-probe/tetgen.cpp
./cocos/gi/light-probe/tetgen.h
./cocos/platform/openharmony/napi/**
./tools/**
./vendor/**
+9 -4
View File
@@ -3725,9 +3725,14 @@ if(APPLE)
"$(inherited)"
${CC_EXTERNAL_LIBS}
)
if(CMAKE_OSX_ARCHITECTURES)
set(_CC_ENGINE_ARCHS "${CMAKE_OSX_ARCHITECTURES}")
else()
set(_CC_ENGINE_ARCHS "arm64;x86_64")
endif()
set_target_properties(${ENGINE_NAME} PROPERTIES
XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "YES"
OSX_ARCHITECTURES "arm64;x86_64"
OSX_ARCHITECTURES "${_CC_ENGINE_ARCHS}"
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/archives
)
if(MACOSX)
@@ -3739,9 +3744,9 @@ if(APPLE)
)
elseif(IOS)
if("${XCODE_VERSION}" VERSION_GREATER_EQUAL "15.0")
# For Xcode 15 and newer, add extra link flags to fix crash in __cxx_global_var_init.
message(STATUS "Using Xcode 15 or newer, adding extra link flags: -Wl,-ld_classic.")
if("${XCODE_VERSION}" VERSION_GREATER_EQUAL "15.0" AND "${XCODE_VERSION}" VERSION_LESS "15.1")
# Xcode 15.0 new linker crashes on weak symbols (114813650), fixed in 15.1.
message(STATUS "Xcode ${XCODE_VERSION}: adding -Wl,-ld_classic to work around weak symbol crash.")
target_link_options(${ENGINE_NAME} PUBLIC -Wl,-ld_classic)
endif()
+1 -1
View File
@@ -126,7 +126,7 @@ if("$ENV{COCOS_ENGINE_DEV}" EQUAL "1")
set(WERROR_FLAGS "-Werror -Werror=return-type") # -Wshorten-64-to-32 -Werror=return-type
if(APPLE)
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-deprecated-declarations -Wno-deprecated-builtins -Wno-unqualified-std-cast-call")
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-deprecated-declarations -Wno-deprecated-builtins -Wno-unqualified-std-cast-call -Wno-nontrivial-memcall")
elseif(LINUX)
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-nullability-completeness -Wno-deprecated-declarations")
elseif(ANDROID)
+29 -27
View File
@@ -40,16 +40,16 @@ int32_t sorting2DCount{0};
CC_FORCE_INLINE void fillIndexBuffers(RenderDrawInfo* drawInfo) { // NOLINT(readability-convert-member-functions-to-static)
uint16_t* ib = drawInfo->getIDataBuffer();
UIMeshBuffer* buffer = drawInfo->getMeshBuffer();
uint32_t indexOffset = buffer->getIndexOffset();
uint16_t* indexb = drawInfo->getIbBuffer();
uint32_t indexCount = drawInfo->getIbCount();
memcpy(&ib[indexOffset], indexb, indexCount * sizeof(uint16_t));
indexOffset += indexCount;
buffer->setIndexOffset(indexOffset);
}
@@ -83,7 +83,7 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) {
uint32_t size = drawInfo->getVbCount() * stride;
float* vbBuffer = drawInfo->getVbBuffer();
Color temp = entity->getColor();
uint32_t offset = 0;
for (int i = 0; i < size; i += stride) {
offset = i + 5;
@@ -91,9 +91,9 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) {
// Spine set 'UIRenderer._useVertexOpacity = true', it uses RGBA32 (4 bytes) color and fills color in Skeleton._updateColor and spine/simple.ts assembler.
// So for Spine rendering, it will never go here to fill color.
vbBuffer[offset] = static_cast<float>(temp.r) / 255.0F;
vbBuffer[offset+1] = static_cast<float>(temp.g) / 255.0F;
vbBuffer[offset+2] = static_cast<float>(temp.b) / 255.0F;
vbBuffer[offset+3] = entity->getOpacity();
vbBuffer[offset + 1] = static_cast<float>(temp.g) / 255.0F;
vbBuffer[offset + 2] = static_cast<float>(temp.b) / 255.0F;
vbBuffer[offset + 3] = entity->getOpacity();
}
}
@@ -110,7 +110,7 @@ Batcher2d::Batcher2d(Root* root)
_root = root;
_device = _root->getDevice();
_stencilManager = StencilManager::getInstance();
_recordedRendererInfoQueue.reserve(100);
}
@@ -138,7 +138,7 @@ Batcher2d::~Batcher2d() { // NOLINT
_maskAttributes.clear();
}
ccstd::vector<RecordedRendererInfo> &Batcher2d::getRecordedRendererInfoQueue() {
ccstd::vector<RecordedRendererInfo>& Batcher2d::getRecordedRendererInfoQueue() {
return _recordedRendererInfoQueue;
}
@@ -170,11 +170,11 @@ void Batcher2d::fillBuffersAndMergeBatches() {
for (auto* rootNode : _rootNodeArr) {
// _batches will add by generateBatch
walk(rootNode, 1, false);
if (ENABLE_SORTING_2D && sorting2DCount > 0) {
flushRecordedUIRenderers();
}
generateBatch(_currEntity, _currDrawInfo);
auto* scene = rootNode->getScene()->getRenderScene();
@@ -186,7 +186,7 @@ void Batcher2d::fillBuffersAndMergeBatches() {
}
}
void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recursion)
void Batcher2d::handleUIRenderer(RenderEntity* entity) { // NOLINT(misc-no-recursion)
uint32_t size = entity->getRenderDrawInfosSize();
for (uint32_t i = 0; i < size; i++) {
auto* drawInfo = entity->getRenderDrawInfoAt(i);
@@ -195,25 +195,25 @@ void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recur
entity->setVBColorDirty(false);
}
int32_t Batcher2d::recordUIRenderer(RenderEntity *entity) {
int32_t Batcher2d::recordUIRenderer(RenderEntity* entity) {
if (!ENABLE_SORTING_2D) return -1;
auto &queue = getRecordedRendererInfoQueue();
auto &info = queue.emplace_back();
auto& queue = getRecordedRendererInfoQueue();
auto& info = queue.emplace_back();
info.renderEntity = entity;
return static_cast<int32_t>(queue.size() - 1);
}
void Batcher2d::flushRecordedUIRenderers() { // NOLINT(misc-no-recursion)
if (!ENABLE_SORTING_2D) return;
auto &queue = getRecordedRendererInfoQueue();
auto& queue = getRecordedRendererInfoQueue();
if (queue.empty()) return;
std::stable_sort(queue.begin(), queue.end(), [](const auto &a, const auto &b){
std::stable_sort(queue.begin(), queue.end(), [](const auto& a, const auto& b) {
return a.renderEntity->getPriority() < b.renderEntity->getPriority();
});
for (const auto &info : queue) {
auto *entity = info.renderEntity;
for (const auto& info : queue) {
auto* entity = info.renderEntity;
if (entity) {
handleUIRenderer(entity);
}
@@ -227,13 +227,13 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
}
bool breakWalk = false;
auto* entity = static_cast<RenderEntity*>(node->getUserData());
const bool isCurrentColorDirty = node->_isColorDirty() || parentColorDirty;
const float localOpacity = node->_getLocalOpacity();
// Keep the same logic as which in batcher-2d.ts
const float finalOpacity = parentOpacity * localOpacity * (entity ? entity->getColorAlpha() : 1.F);
node->_setFinalOpacity(finalOpacity);
const bool visible = math::isNotEqualF(finalOpacity, 0);
if (entity) {
@@ -244,7 +244,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
entity->setOpacity(finalOpacity);
entity->setVBColorDirty(true);
}
if (ENABLE_SORTING_2D && sorting2DCount > 0) {
if (entity->getIsMask()) {
flushRecordedUIRenderers();
@@ -257,7 +257,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
handleUIRenderer(entity);
}
}
if (entity->getRenderEntityType() == RenderEntityType::CROSSED) {
breakWalk = true;
}
@@ -271,7 +271,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
walk(child, thisOpacity, isCurrentColorDirty);
}
}
if (isCurrentColorDirty) {
node->_setColorDirty(false);
}
@@ -283,7 +283,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
flushRecordedUIRenderers();
}
}
if (visible && _stencilManager->getMaskStackSize() > 0) {
handlePostRender(entity);
}
@@ -521,7 +521,7 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) {
curdrawBatch->setFirstIndex(indexOffset);
curdrawBatch->setIndexCount(indexCount);
curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash);
const auto &passes = curdrawBatch->getPasses();
const auto& passes = curdrawBatch->getPasses();
if (!passes.empty()) {
const auto& pass = passes.at(0);
if (entity->getUseLocal()) {
@@ -695,6 +695,8 @@ void Batcher2d::reset() {
_currSampler = nullptr;
// stencilManager
_stencilManager->setMaskStackSize(0);
_stencilManager->setStencilStage(static_cast<uint32_t>(StencilStage::DISABLED));
}
void Batcher2d::insertMaskBatch(RenderEntity* entity) {
+7 -7
View File
@@ -41,13 +41,13 @@ using UIMeshBufferArray = ccstd::vector<UIMeshBuffer*>;
using UIMeshBufferMap = ccstd::unordered_map<uint16_t, UIMeshBufferArray>;
struct RecordedRendererInfo {
RenderEntity *renderEntity{nullptr};
RenderEntity* renderEntity{nullptr};
};
class Batcher2d final {
public:
static void setSorting2DCount(int32_t v);
Batcher2d();
explicit Batcher2d(Root* root);
~Batcher2d();
@@ -87,10 +87,10 @@ private:
void createClearModel();
gfx::DescriptorSet* getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, const gfx::DescriptorSetLayout* dsLayout);
ccstd::vector<RecordedRendererInfo> &getRecordedRendererInfoQueue();
void handleUIRenderer(RenderEntity *entity);
int32_t recordUIRenderer(RenderEntity *entity);
ccstd::vector<RecordedRendererInfo>& getRecordedRendererInfoQueue();
void handleUIRenderer(RenderEntity* entity);
int32_t recordUIRenderer(RenderEntity* entity);
void flushRecordedUIRenderers();
StencilManager* _stencilManager{nullptr};
@@ -103,7 +103,7 @@ private:
// manage memory manually
ccstd::vector<scene::DrawBatch2D*> _batches;
memop::Pool<scene::DrawBatch2D> _drawBatchPool;
ccstd::vector<RecordedRendererInfo> _recordedRendererInfoQueue;
// weak reference
+5 -5
View File
@@ -24,8 +24,8 @@
#pragma once
#include "2d/renderer/UIMeshBuffer.h"
#include "base/Ptr.h"
#include "base/Macros.h"
#include "base/Ptr.h"
#include "base/TypeDef.h"
#include "bindings/utils/BindingUtils.h"
#include "core/ArrayBuffer.h"
@@ -115,7 +115,7 @@ public:
inline void setIsMeshBuffer(bool isMeshBuffer) {
_drawInfoAttrs._isMeshBuffer = isMeshBuffer ? 1 : 0;
}
inline bool isVertexPositionInWorld() const {
return _drawInfoAttrs._isVertexPositionInWorld != 0;
}
@@ -262,9 +262,9 @@ private:
struct DrawInfoAttrs {
RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP};
bool _vertDirty{false};
uint8_t _isMeshBuffer: 1;
uint8_t _isVertexPositionInWorld: 1;
uint8_t _padding: 6;
uint8_t _isMeshBuffer : 1;
uint8_t _isVertexPositionInWorld : 1;
uint8_t _padding : 6;
uint8_t _stride{0};
uint16_t _bufferId{0};
uint16_t _accId{0};
+2 -2
View File
@@ -33,11 +33,11 @@ RenderEntity::RenderEntity(RenderEntityType type) : _renderEntityType(type) {
} else {
ccnew_placement(&_dynamicDrawInfos) ccstd::vector<RenderDrawInfo*>();
}
_entityAttrLayout.enabledIndex = 0;
_entityAttrLayout.useLocal = 0;
_entityAttrLayout.paddings = 0;
_entitySharedBufferActor.initialize(&_entityAttrLayout, sizeof(EntityAttrLayout));
}
+9 -9
View File
@@ -49,7 +49,7 @@ enum class MaskMode : uint8_t {
MASK_NODE_INVERTED
};
enum class FillColorType: uint8_t {
enum class FillColorType : uint8_t {
COLOR = 0,
VERTEX,
};
@@ -62,9 +62,9 @@ struct EntityAttrLayout {
uint8_t colorA{255};
uint8_t maskMode{0};
FillColorType fillColorType{FillColorType::COLOR};
uint8_t enabledIndex: 1;
uint8_t useLocal: 1;
uint8_t paddings: 6;
uint8_t enabledIndex : 1;
uint8_t useLocal : 1;
uint8_t paddings : 6;
uint8_t paddings2{0};
};
@@ -99,7 +99,7 @@ public:
inline void setUseLocal(bool useLocal) {
_entityAttrLayout.useLocal = useLocal;
}
inline FillColorType getFillColorType() const { return _entityAttrLayout.fillColorType; }
inline Node* getNode() const { return _node; }
@@ -142,7 +142,7 @@ public:
inline RenderDrawInfo* getRenderDrawInfoAt(uint32_t index) {
return _renderEntityType == RenderEntityType::STATIC ? &(_staticDrawInfos[index]) : _dynamicDrawInfos[index];
}
inline uint32_t getPriority() const { return _entityAttrLayout.priority; }
private:
@@ -152,7 +152,7 @@ private:
// weak reference
Node* _renderTransform{nullptr};
bindings::NativeMemorySharedToScriptActor _entitySharedBufferActor;
union {
@@ -160,13 +160,13 @@ private:
ccstd::vector<RenderDrawInfo*> _dynamicDrawInfos;
};
EntityAttrLayout _entityAttrLayout;
StencilStage _stencilStage{StencilStage::DISABLED};
RenderEntityType _renderEntityType{RenderEntityType::STATIC};
uint8_t _staticDrawInfoSize{0};
bool _vbColorDirty{true};
uint8_t _paddings[1];
float _opacity{1.0F};
};
+3 -3
View File
@@ -23,12 +23,12 @@
****************************************************************************/
#pragma once
#include "base/Ptr.h"
#include "base/Macros.h"
#include "base/Ptr.h"
#include "base/TypeDef.h"
#include "renderer/gfx-base/GFXInputAssembler.h"
#include "renderer/gfx-base/GFXDef-common.h"
#include "renderer/gfx-base/GFXBuffer.h"
#include "renderer/gfx-base/GFXDef-common.h"
#include "renderer/gfx-base/GFXInputAssembler.h"
namespace cc {
+4 -4
View File
@@ -58,13 +58,13 @@ void UIModelProxy::activeSubModels() {
auto* vertexBuffer = _device->createBuffer({
gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::DEVICE,
65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535)
65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535)
_stride,
});
auto* indexBuffer = _device->createBuffer({
gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::DEVICE,
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
sizeof(uint16_t),
});
gfx::BufferList vbReference;
@@ -133,8 +133,8 @@ void UIModelProxy::clear() {
return;
}
const auto& subModels = _model->getSubModels();
for (const auto &subModel : subModels) {
auto *ia = subModel->getInputAssembler();
for (const auto& subModel : subModels) {
auto* ia = subModel->getInputAssembler();
ia->setVertexCount(0);
ia->setIndexCount(0);
}
+2 -2
View File
@@ -531,14 +531,14 @@ void Mesh::initialize() {
uint32_t vertexCount = _struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
#if CC_OPTIMIZE_MESH_DATA
if (vertexCount <= 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
dstStride >>= 1; // Reduce to short.
dstStride >>= 1; // Reduce to short.
dstSize >>= 1;
} else if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
continue; // Ignore this primitive
}
#else
if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
CC_LOG_WARNING("Device does not support UINT element index type and vertexCount (%u) is larger than ushort", vertexCount);
continue;
}
+1 -1
View File
@@ -310,7 +310,7 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome
if (aOptions.has_value()) {
options = aOptions.value();
}
gfx::AttributeList attributes;
uint32_t stream = 0U;
@@ -25,8 +25,8 @@
#define LOG_TAG "AudioDecoderSLES"
#include "base/Macros.h"
#include "audio/android/AudioDecoderSLES.h"
#include "base/Macros.h"
#include "platform/FileUtils.h"
#include <mutex>
+50 -50
View File
@@ -29,9 +29,9 @@
#include <unistd.h>
// for native asset manager
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#endif
#include <sys/types.h>
@@ -45,11 +45,11 @@
#include "base/UTF8.h"
#include "base/memory/Memory.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/android/FileUtils-android.h"
#include "platform/java/jni/JniHelper.h"
#include "platform/java/jni/JniImp.h"
#include "platform/android/FileUtils-android.h"
#include "platform/java/jni/JniHelper.h"
#include "platform/java/jni/JniImp.h"
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#endif
#include "audio/android/AudioDecoder.h"
@@ -68,20 +68,20 @@ namespace {
AudioEngineImpl *gAudioImpl = nullptr;
int outputSampleRate = 44100;
#if CC_PLATFORM == CC_PLATFORM_ANDROID
int bufferSizeInFrames = 192;
int bufferSizeInFrames = 192;
#endif
void getAudioInfo() {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
JNIEnv * env = JniHelper::getEnv();
jclass audioSystem = env->FindClass("android/media/AudioSystem");
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
JNIEnv *env = JniHelper::getEnv();
jclass audioSystem = env->FindClass("android/media/AudioSystem");
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
#else
// In openharmony, setting to 48K does not cause audio delays
outputSampleRate = 48000;
outputSampleRate = 48000;
#endif
}
} // namespace
@@ -123,8 +123,8 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) {
AAsset_close(asset);
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
FileUtilsOpenHarmony* fileUtils = dynamic_cast<FileUtilsOpenHarmony*>(FileUtils::getInstance());
if(fileUtils) {
FileUtilsOpenHarmony *fileUtils = dynamic_cast<FileUtilsOpenHarmony *>(FileUtils::getInstance());
if (fileUtils) {
RawFileDescriptor64 descriptor;
fileUtils->getRawFileDescriptor(url, descriptor);
fd = descriptor.fd;
@@ -189,27 +189,27 @@ bool AudioEngineImpl::init() {
CC_LOG_ERROR("get the engine interface fail");
break;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
// create output mix
const SLInterfaceID outputMixIIDs[] = {};
const SLboolean outputMixReqs[] = {};
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("create output mix fail");
break;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
// create output mix
const SLInterfaceID outputMixIIDs[] = {};
const SLboolean outputMixReqs[] = {};
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("create output mix fail");
break;
}
// realize the output mix
result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("realize the output mix fail");
break;
}
// realize the output mix
result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("realize the output mix fail");
break;
}
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils);
#endif
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils);
#endif
ret = true;
} while (false);
@@ -227,14 +227,14 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
auto audioId = AudioEngine::INVALID_AUDIO_ID;
do {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) {
break;
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
if (_audioPlayerProvider == nullptr)
break;
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) {
break;
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
if (_audioPlayerProvider == nullptr)
break;
#endif
auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
@@ -443,12 +443,12 @@ PCMHeader AudioEngineImpl::getPCMHeader(const char *url) {
CC_LOG_DEBUG("file %s pcm data already cached", url);
return header;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#if CC_PLATFORM == CC_PLATFORM_ANDROID
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(
_engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter);
#endif
#endif
if (decoder == nullptr) {
CC_LOG_DEBUG("decode %s failed, the file formate might not support", url);
return header;
@@ -482,12 +482,12 @@ ccstd::vector<uint8_t> AudioEngineImpl::getOriginalPCMBuffer(const char *url, ui
if (_audioPlayerProvider->getPcmData(url, data)) {
CC_LOG_DEBUG("file %s pcm data already cached", url);
} else {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#if CC_PLATFORM == CC_PLATFORM_ANDROID
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter);
#else
#else
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(
_engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter);
#endif
#endif
if (decoder == nullptr) {
CC_LOG_DEBUG("decode %s failed, the file formate might not support", url);
return pcmData;
+2 -2
View File
@@ -26,9 +26,9 @@
#include <SLES/OpenSLES.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES_Android.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#include <functional>
#include "audio/include/AudioDef.h"
+18 -18
View File
@@ -17,9 +17,9 @@
#pragma once
#include <cstdint>
#include <sys/types.h>
#include <pthread.h>
#include <sys/types.h>
#include <cstdint>
#include "audio/android/AudioBufferProvider.h"
#include "audio/android/AudioResamplerPublic.h"
@@ -160,7 +160,7 @@ private:
struct track_t;
typedef void (*hook_t)(track_t *t, int32_t *output, size_t numOutFrames, int32_t *temp, int32_t *aux); //NOLINT(modernize-use-using)
static const int BLOCKSIZE = 16; // 4 cache lines
static const int BLOCKSIZE = 16; // 4 cache lines
struct track_t {
uint32_t needs;
@@ -288,19 +288,19 @@ private:
};
// bitmask of allocated track names, where bit 0 corresponds to TRACK0 etc.
uint32_t mTrackNames;// NOLINT(readability-identifier-naming)
uint32_t mTrackNames; // NOLINT(readability-identifier-naming)
// bitmask of configured track names; ~0 if maxNumTracks == MAX_NUM_TRACKS,
// but will have fewer bits set if maxNumTracks < MAX_NUM_TRACKS
const uint32_t mConfiguredNames;// NOLINT(readability-identifier-naming)
const uint32_t mConfiguredNames; // NOLINT(readability-identifier-naming)
const uint32_t mSampleRate;// NOLINT(readability-identifier-naming)
const uint32_t mSampleRate; // NOLINT(readability-identifier-naming)
//cjh NBLog::Writer mDummyLog;
public:
//cjh void setLog(NBLog::Writer* log);
private:
state_t mState __attribute__((aligned(32)));// NOLINT(readability-identifier-naming)
state_t mState __attribute__((aligned(32))); // NOLINT(readability-identifier-naming)
// Call after changing either the enabled status of a track, or parameters of an enabled track.
// OK to call more often than that, but unnecessary.
@@ -309,19 +309,19 @@ private:
bool setChannelMasks(int name,
audio_channel_mask_t trackChannelMask, audio_channel_mask_t mixerChannelMask);
static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void volumeRampStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp, int32_t *aux);
static void volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp,
int32_t *aux);
static void process__validate(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__nop(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__validate(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__nop(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static int64_t calculateOutputPTS(const track_t &t, int64_t basePTS,
int outputFrameIndex);
@@ -347,11 +347,11 @@ private:
// multi-format process hooks
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void process_NoResampleOneTrack(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process_NoResampleOneTrack(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
// multi-format track hooks
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void track__NoResample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
@@ -33,8 +33,8 @@
#include "base/std/container/vector.h"
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode
#define MAX_AUDIO_BUFFER_SIZE 4458
// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode
#define MAX_AUDIO_BUFFER_SIZE 4458
#endif
namespace cc {
@@ -42,14 +42,14 @@
#include "base/ThreadPool.h"
#include "base/memory/Memory.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/system_properties.h>
#include "audio/android/UrlAudioPlayer.h"
#include "audio/android/PcmAudioService.h"
#include <sys/system_properties.h>
#include "audio/android/PcmAudioService.h"
#include "audio/android/UrlAudioPlayer.h"
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "cocos/platform/FileUtils.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#include "audio/openharmony/UrlAudioPlayer.h"
#include "audio/openharmony/PcmAudioService.h"
#include "audio/openharmony/PcmAudioService.h"
#include "audio/openharmony/UrlAudioPlayer.h"
#include "cocos/platform/FileUtils.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#endif
#include <algorithm> // for std::find_if
#include <cstdlib>
@@ -107,12 +107,9 @@ AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outp
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, int deviceSampleRate,
const FdGetterCallback &fdGetterCallback,
const FdGetterCallback &fdGetterCallback,
ICallerThreadUtils *callerThreadUtils)
: _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback),
_callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr),
_mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2))
{
: _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) {
_mixController = ccnew AudioMixerController(_deviceSampleRate, 2);
_pcmAudioService = ccnew PcmAudioService();
_pcmAudioService->init(_mixController, 2, deviceSampleRate, &_bufferSizeInFrames);
@@ -364,13 +361,13 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
fileSize = length;
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
RawFileDescriptor64 descriptor;
FileUtilsOpenHarmony* fileUtils = static_cast<FileUtilsOpenHarmony*>(FileUtils::getInstance());
if(!fileUtils) {
FileUtilsOpenHarmony *fileUtils = static_cast<FileUtilsOpenHarmony *>(FileUtils::getInstance());
if (!fileUtils) {
return info;
}
FileUtils::Status status = fileUtils->getRawFileDescriptor(audioFilePath, descriptor);
if(status != FileUtils::Status::OK || descriptor.fd<= 0) {
if (status != FileUtils::Status::OK || descriptor.fd <= 0) {
ALOGE("Failed to open file descriptor for %s", audioFilePath.c_str());
return info;
}
@@ -412,9 +409,9 @@ bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(read
extension = audioFileInfo.url.substr(pos);
}
auto *iter = std::find_if(std::begin(gAudioFileIndicator), std::end(gAudioFileIndicator),
[&extension](const AudioFileIndicator &judge) -> bool {
return judge.extension == extension;
});
[&extension](const AudioFileIndicator &judge) -> bool {
return judge.extension == extension;
});
if (iter != std::end(gAudioFileIndicator)) {
// ALOGV("isSmallFile: found: %s: ", iter->extension.c_str());
@@ -472,19 +469,18 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer(
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI;
auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
if (!ret) {
SL_SAFE_DELETE(urlPlayer);
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, info.assetFd, info.start, info.length);
if (!ret)
{
if (urlPlayer != nullptr) {
if (!ret) {
if (urlPlayer != nullptr) {
delete urlPlayer;
urlPlayer = nullptr;
urlPlayer = nullptr;
}
}
#endif
+17 -18
View File
@@ -18,9 +18,9 @@
#include <cstdint>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/log.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#include <android/log.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#endif
#include "audio/android/AudioBufferProvider.h"
@@ -108,21 +108,20 @@ protected:
int64_t calculateOutputPTS(int outputFrameIndex);
const int32_t mChannelCount;// NOLINT(readability-identifier-naming)
const int32_t mSampleRate;// NOLINT(readability-identifier-naming)
int32_t mInSampleRate;// NOLINT(readability-identifier-naming)
AudioBufferProvider::Buffer mBuffer;// NOLINT(readability-identifier-naming)
const int32_t mChannelCount; // NOLINT(readability-identifier-naming)
const int32_t mSampleRate; // NOLINT(readability-identifier-naming)
int32_t mInSampleRate; // NOLINT(readability-identifier-naming)
AudioBufferProvider::Buffer mBuffer; // NOLINT(readability-identifier-naming)
union {
int16_t mVolume[2];// NOLINT(readability-identifier-naming)
uint32_t mVolumeRL;// NOLINT(readability-identifier-naming)
int16_t mVolume[2]; // NOLINT(readability-identifier-naming)
uint32_t mVolumeRL; // NOLINT(readability-identifier-naming)
};
int16_t mTargetVolume[2];// NOLINT(readability-identifier-naming)
size_t mInputIndex;// NOLINT(readability-identifier-naming)
int32_t mPhaseIncrement;// NOLINT(readability-identifier-naming)
uint32_t mPhaseFraction;// NOLINT(readability-identifier-naming)
uint64_t mLocalTimeFreq;// NOLINT(readability-identifier-naming)
int64_t mPTS;// NOLINT(readability-identifier-naming)
int16_t mTargetVolume[2]; // NOLINT(readability-identifier-naming)
size_t mInputIndex; // NOLINT(readability-identifier-naming)
int32_t mPhaseIncrement; // NOLINT(readability-identifier-naming)
uint32_t mPhaseFraction; // NOLINT(readability-identifier-naming)
uint64_t mLocalTimeFreq; // NOLINT(readability-identifier-naming)
int64_t mPTS; // NOLINT(readability-identifier-naming)
// returns the inFrameCount required to generate outFrameCount frames.
//
@@ -155,7 +154,7 @@ protected:
return (static_cast<size_t>(outFrameCount) * mInSampleRate + (mSampleRate - 1)) / mSampleRate;
}
inline float clampFloatVol(float volume) {//NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static)
inline float clampFloatVol(float volume) { //NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static)
float ret = 0.0F;
if (volume > UNITY_GAIN_FLOAT) {
ret = UNITY_GAIN_FLOAT;
@@ -166,7 +165,7 @@ protected:
}
private:
const src_quality mQuality;// NOLINT(readability-identifier-naming)
const src_quality mQuality; // NOLINT(readability-identifier-naming)
// Return 'true' if the quality level is supported without explicit request
static bool qualityIsSupported(src_quality quality);
@@ -19,8 +19,8 @@
#include <stdint.h>
#include <sys/types.h>
#include "audio/android/AudioResampler.h"
#include "audio/android/AudioBufferProvider.h"
#include "audio/android/AudioResampler.h"
namespace cc {
// ----------------------------------------------------------------------------
+2 -2
View File
@@ -29,9 +29,9 @@
#include <SLES/OpenSLES.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES_Android.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#include <functional>
+19 -19
View File
@@ -25,28 +25,28 @@
#define LOG_TAG "PcmAudioService"
#include "base/Macros.h"
#include "audio/android/PcmAudioService.h"
#include "audio/android/AudioMixerController.h"
#include "audio/android/utils/Compat.h"
#include "base/Macros.h"
namespace cc {
static ccstd::vector<char> __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static ccstd::vector<char> __silenceData; //NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
#define AUDIO_PLAYER_BUFFER_COUNT (2)
class SLPcmAudioPlayerCallbackProxy {
public:
#if CC_PLATFORM == CC_PLATFORM_ANDROID
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context) {
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context){
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context, SLuint32 size) {
#endif
auto *thiz = reinterpret_cast<PcmAudioService *>(context);
thiz->bqFetchBufferCallback(bq);
}
};
thiz->bqFetchBufferCallback(bq);
}
}; // namespace cc
PcmAudioService::PcmAudioService(SLEngineItf engineItf, SLObjectItf outputMixObject)
: _engineItf(engineItf), _outputMixObj(outputMixObject), _playObj(nullptr), _playItf(nullptr), _volumeItf(nullptr), _bufferQueueItf(nullptr), _numChannels(-1), _sampleRate(-1), _bufferSizeInBytes(0), _controller(nullptr) {
@@ -59,12 +59,12 @@ PcmAudioService::~PcmAudioService() {
}
bool PcmAudioService::enqueue() {
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
if (_controller->hasPlayingTacks()) {
if (_controller->isPaused()) {
SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size());
@@ -141,7 +141,7 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
SLresult r;
r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req);//NOLINT(bugprone-sizeof-expression)
r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req); //NOLINT(bugprone-sizeof-expression)
SL_RETURN_VAL_IF_FAILED(r, false, "CreateAudioPlayer failed");
r = (*_playObj)->Realize(_playObj, SL_BOOLEAN_FALSE);
@@ -162,12 +162,12 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
if (__silenceData.empty()) {
__silenceData.resize(_numChannels * _bufferSizeInBytes, 0x00);
}
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size());
SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf Enqueue failed");
@@ -26,17 +26,17 @@
#define LOG_TAG "UrlAudioPlayer"
#include "audio/android/UrlAudioPlayer.h"
#include "audio/android/ICallerThreadUtils.h"
#include "base/std/container/vector.h"
#include "base/Macros.h"
#include <cmath>
#include <algorithm> // for std::find
#include <cmath>
#include "audio/android/ICallerThreadUtils.h"
#include "base/Macros.h"
#include "base/std/container/vector.h"
namespace {
std::mutex __playerContainerMutex;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
ccstd::vector<cc::UrlAudioPlayer *> __playerContainer;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::once_flag __onceFlag;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::mutex __playerContainerMutex; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
ccstd::vector<cc::UrlAudioPlayer *> __playerContainer; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::once_flag __onceFlag; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
} // namespace
@@ -216,7 +216,7 @@ float UrlAudioPlayer::getDuration() const {
if (duration == SL_TIME_UNKNOWN) {
return -1.0F;
} else {// NOLINT(readability-else-after-return)
} else { // NOLINT(readability-else-after-return)
const_cast<UrlAudioPlayer *>(this)->_duration = duration / 1000.0F;
if (_duration <= 0) {
+3 -3
View File
@@ -22,10 +22,10 @@
#include <strings.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
#ifdef __cplusplus
#ifdef __cplusplus
extern "C" {
#endif
@@ -41,7 +41,7 @@ static inline int popcountll(unsigned long long x) {
return __builtin_popcountll(x);
}
#ifdef __cplusplus
#ifdef __cplusplus
}
#endif
+35 -36
View File
@@ -34,10 +34,10 @@
#include <time.h>
#include <unistd.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/log.h>
#include <android/log.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <hilog/log.h>
#define LOG_VERBOSE LOG_INFO
#include <hilog/log.h>
#define LOG_VERBOSE LOG_INFO
#endif
#ifdef __cplusplus
@@ -90,11 +90,11 @@ extern "C" {
* Simplified macro to send a verbose log message using the current LOG_TAG.
*/
#ifndef ALOGV
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
#endif
#if LOG_NDEBUG
#define ALOGV(...) \
do { \
@@ -413,23 +413,23 @@ extern "C" {
* is -inverted- from the normal assert() semantics.
*/
#ifndef LOG_ALWAYS_FATAL_IF
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL_IF(cond, ...) \
((__predict_false(cond)) \
? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
: (void)0)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0 )
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL_IF(cond, ...) \
((__predict_false(cond)) \
? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
: (void)0)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0)
#endif
#endif
#ifndef LOG_ALWAYS_FATAL
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL(...) \
(((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL(...) \
(((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#endif
/*
@@ -476,26 +476,25 @@ extern "C" {
* The second argument may be NULL or "" to indicate the "global" tag.
*/
#ifndef ALOG
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define ALOG(priority, tag, ...) \
LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define ALOG(priority, tag, ...) \
LOG_PRI(priority, tag, __VA_ARGS__)
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define ALOG(priority, tag, ...) \
LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define ALOG(priority, tag, ...) \
LOG_PRI(priority, tag, __VA_ARGS__)
#endif
#endif
#endif
/*
* Log macro that allows you to specify a number for the priority.
*/
#ifndef LOG_PRI
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_PRI(priority, tag, ...) \
android_printLog(priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_PRI(priority, tag, ...) ((void) OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_PRI(priority, tag, ...) \
android_printLog(priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_PRI(priority, tag, ...) ((void)OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#endif
/*
+8 -9
View File
@@ -17,16 +17,15 @@
#ifndef COCOS_LIB_UTILS_COMPAT_H
#define COCOS_LIB_UTILS_COMPAT_H
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <unistd.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <unistd.h>
#elif CC_PLATFORM == CC_PLATFORM_WINDOWS
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_OpenHarmony.h>
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_OpenHarmony.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#if defined(__APPLE__)
@@ -97,11 +96,11 @@ static inline ssize_t pwrite64(int fd, const void *buf, size_t nbytes, off64_t o
#if CC_PLATFORM == CC_PLATFORM_ANDROID
typedef SLAndroidSimpleBufferQueueItf CCSLBufferQueueItf;
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
typedef SLOHBufferQueueItf CCSLBufferQueueItf;
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE
#define __unused
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE
#define __unused
#endif
#endif /* COCOS_LIB_UTILS_COMPAT_H */
+1 -1
View File
@@ -17,8 +17,8 @@
#ifndef COCOS_ERRORS_H
#define COCOS_ERRORS_H
#include <sys/types.h>
#include <errno.h>
#include <sys/types.h>
namespace cc {
+1 -1
View File
@@ -27,8 +27,8 @@
#import <OpenAL/al.h>
#include <mutex>
#include <functional>
#include <mutex>
#include "base/std/container/string.h"
#include "audio/apple/AudioMacros.h"
@@ -19,7 +19,7 @@
#include <stdint.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
#include "audio/android/audio.h"
@@ -25,7 +25,7 @@
#include <stdio.h>
#include <stdlib.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
/* The memcpy_* conversion routines are designed to work in-place on same dst as src
@@ -178,7 +178,7 @@ bool AudioEngineImpl::init() {
alcMakeContextCurrent(sALContext);
std::fill(std::begin(_alSources), std::end(_alSources), 0);
std::fill(std::begin(_alSources), std::end(_alSources), 0);
alGenSources(MAX_AUDIOINSTANCES, _alSources);
auto alError = alGetError();
@@ -26,9 +26,9 @@ THE SOFTWARE.
#define LOG_TAG "PcmAudioService"
#include "audio/openharmony/PcmAudioService.h"
#include <deviceinfo.h>
#include "audio/android/AudioMixerController.h"
#include "audio/android/cutils/log.h"
#include <deviceinfo.h>
namespace cc {
@@ -106,10 +106,10 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
OH_AudioRenderer_Callbacks callbacks;
static int sdkApi = OH_GetSdkApiVersion();
if(sdkApi >= 21) {
if (sdkApi >= 21) {
callbacks.OH_AudioRenderer_OnWriteData = nullptr;
} else {
callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast<int32_t (*)(OH_AudioRenderer*,void* ,void* ,int32_t)>(AudioRendererOnWriteData);
callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast<int32_t (*)(OH_AudioRenderer *, void *, void *, int32_t)>(AudioRendererOnWriteData);
}
callbacks.OH_AudioRenderer_OnInterruptEvent = AudioRendererOnInterrupt;
callbacks.OH_AudioRenderer_OnError = nullptr;
@@ -118,9 +118,9 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
if (ret != AUDIOSTREAM_SUCCESS) {
return false;
}
if(sdkApi >= 21) {
ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this);
if (sdkApi >= 21) {
ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this);
if (ret != AUDIOSTREAM_SUCCESS) {
return false;
}
@@ -26,8 +26,8 @@ THE SOFTWARE.
#define LOG_TAG "UrlAudioPlayer"
#include "audio/openharmony/UrlAudioPlayer.h"
#include <map>
#include <algorithm> // for std::find
#include <map>
#include "audio/android/ICallerThreadUtils.h"
#include "audio/android/cutils/log.h"
#include "cocos/application/ApplicationManager.h"
+12 -12
View File
@@ -209,23 +209,23 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) {
::LogLevel ohosLoglevel = ::LogLevel::LOG_DEBUG;
switch (level) {
case LogLevel::LEVEL_DEBUG:
ohosLoglevel = ::LogLevel::LOG_DEBUG;
break;
ohosLoglevel = ::LogLevel::LOG_DEBUG;
break;
case LogLevel::INFO:
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
case LogLevel::WARN:
ohosLoglevel = ::LogLevel::LOG_WARN;
break;
ohosLoglevel = ::LogLevel::LOG_WARN;
break;
case LogLevel::ERR:
ohosLoglevel = ::LogLevel::LOG_ERROR;
break;
ohosLoglevel = ::LogLevel::LOG_ERROR;
break;
case LogLevel::FATAL:
ohosLoglevel = ::LogLevel::LOG_FATAL;
break;
ohosLoglevel = ::LogLevel::LOG_FATAL;
break;
default:
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
ohosLoglevel = ::LogLevel::LOG_INFO;
break;
}
OH_LOG_Print(LOG_APP, ohosLoglevel, LOG_DOMAIN, "HMG_LOG", "%{public}s", buff);
#else
+3 -3
View File
@@ -346,7 +346,7 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() {
// fixed #4123: Save the callback functions, they must be invoked after '_performMutex.unlock()', otherwise if new functions are added in callback, it will cause thread deadlock.
auto temp = std::move(_functionsToPerform);
_performMutex.unlock();
auto iter = temp.begin();
for (; iter != temp.end(); ++iter) {
nowTime = std::chrono::steady_clock::now();
@@ -355,10 +355,10 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() {
if (passedMS > 16) {
break;
}
(*iter)();
}
std::lock_guard<std::mutex> lk(_performMutex);
_functionsToPerform.insert(_functionsToPerform.begin(), std::make_move_iterator(iter), std::make_move_iterator(temp.end()));
}
+1 -1
View File
@@ -268,7 +268,7 @@ public:
* @js NA
*/
void removeAllFunctionsToBePerformedInCocosThread();
void runFunctionsToBePerformedInCocosThread();
bool isCurrentTargetSalvaged() const { return _currentTargetSalvaged; };
+25 -25
View File
@@ -42,38 +42,38 @@ using index_t = int32_t;
#define CC_ENUM_CONVERSION_OPERATOR(T) \
inline std::underlying_type_t<T> toNumber(const T v) { return static_cast<std::underlying_type_t<T>>(v); }
#define CC_ENUM_BITWISE_OPERATORS(T) \
constexpr bool operator!(const T v) { return !static_cast<std::underlying_type_t<T>>(v); } \
constexpr T operator~(const T v) { return static_cast<T>(~static_cast<std::underlying_type_t<T>>(v)); } \
#define CC_ENUM_BITWISE_OPERATORS(T) \
constexpr bool operator!(const T v) { return !static_cast<std::underlying_type_t<T>>(v); } \
constexpr T operator~(const T v) { return static_cast<T>(~static_cast<std::underlying_type_t<T>>(v)); } \
constexpr bool operator||(const T lhs, const T rhs) { return (static_cast<std::underlying_type_t<T>>(lhs) || static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr bool operator&&(const T lhs, const T rhs) { return (static_cast<std::underlying_type_t<T>>(lhs) && static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator|(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) | static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator&(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) & static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator^(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) ^ static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator+(const T lhs, const T rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) + static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr T operator+(const T lhs, bool rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) + rhs); } \
constexpr T operator+(const T lhs, bool rhs) { return static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) + rhs); } \
constexpr void operator|=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) | static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr void operator&=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) & static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr void operator^=(T &lhs, const T rhs) { lhs = static_cast<T>(static_cast<std::underlying_type_t<T>>(lhs) ^ static_cast<std::underlying_type_t<T>>(rhs)); } \
constexpr bool hasFlag(const T flags, const T flagToTest) { \
using ValueType = std::underlying_type_t<T>; \
CC_ASSERT((static_cast<ValueType>(flagToTest) & (static_cast<ValueType>(flagToTest) - 1)) == 0); \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagToTest)) != 0; \
} \
constexpr bool hasAnyFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) != 0; \
} \
constexpr bool hasAllFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) == static_cast<ValueType>(flagsToTest); \
} \
constexpr T addFlags(T &flags, const T flagsToAdd) { \
flags |= flagsToAdd; \
return flags; \
} \
constexpr T removeFlags(T &flags, const T flagsToRemove) { \
flags &= ~flagsToRemove; \
return flags; \
} \
constexpr bool hasFlag(const T flags, const T flagToTest) { \
using ValueType = std::underlying_type_t<T>; \
CC_ASSERT((static_cast<ValueType>(flagToTest) & (static_cast<ValueType>(flagToTest) - 1)) == 0); \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagToTest)) != 0; \
} \
constexpr bool hasAnyFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) != 0; \
} \
constexpr bool hasAllFlags(const T flags, const T flagsToTest) { \
using ValueType = std::underlying_type_t<T>; \
return (static_cast<ValueType>(flags) & static_cast<ValueType>(flagsToTest)) == static_cast<ValueType>(flagsToTest); \
} \
constexpr T addFlags(T &flags, const T flagsToAdd) { \
flags |= flagsToAdd; \
return flags; \
} \
constexpr T removeFlags(T &flags, const T flagsToRemove) { \
flags &= ~flagsToRemove; \
return flags; \
} \
CC_ENUM_CONVERSION_OPERATOR(T)
+2 -2
View File
@@ -34,8 +34,8 @@
#include "ConvertUTF/ConvertUTF.h"
#if CC_USE_SIMD_UTF
#include "simdutf/simdutf.cpp" //NOLINT
#include "simdutf/simdutf.h"
#include "simdutf/simdutf.cpp" //NOLINT
#include "simdutf/simdutf.h"
#endif
#include "base/Log.h"
+1 -1
View File
@@ -24,8 +24,8 @@
#include "MessageQueue.h"
#include "AutoReleasePool.h"
#include "base/Utils.h"
#include "base/Log.h"
#include "base/Utils.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <unistd.h>
@@ -37,7 +37,7 @@ HandleObject::HandleObject(Object *obj)
}
}
HandleObject::HandleObject(HandleObject &&o) noexcept{
HandleObject::HandleObject(HandleObject &&o) noexcept {
_obj = o._obj;
o._obj = nullptr;
}
@@ -49,7 +49,7 @@ HandleObject::~HandleObject() {
}
}
HandleObject& HandleObject::operator=(HandleObject &&o) noexcept {
HandleObject &HandleObject::operator=(HandleObject &&o) noexcept {
_obj = o._obj;
o._obj = nullptr;
return *this;
@@ -98,10 +98,10 @@ public:
return (_obj == nullptr);
}
HandleObject(HandleObject &&) noexcept;
HandleObject& operator=(HandleObject &&) noexcept;
HandleObject &operator=(HandleObject &&) noexcept;
HandleObject(const HandleObject &) = delete;
HandleObject& operator=(const HandleObject &) = delete;
HandleObject &operator=(const HandleObject &) = delete;
void *operator new(size_t size) = delete;
void operator delete(void *, size_t) = delete;
@@ -169,12 +169,12 @@ private:
if (kls != nullptr && kls != itr->second->_getClass()) {
continue;
}
// JS object may be null when it is obtained on zhe JSVM brach of the 5.1 ROMS
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM
if(itr->second->_getJSObject() == nullptr) {
continue;
}
#endif
// JS object may be null when it is obtained on zhe JSVM brach of the 5.1 ROMS
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM
if (itr->second->_getJSObject() == nullptr) {
continue;
}
#endif
eleCount++;
CC_ASSERT_LT(eleCount, 2);
eachCallback(itr->second);
-2
View File
@@ -43,12 +43,10 @@
#include "chakracore/Object.h"
#endif
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI
#include "napi/Object.h"
#endif
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM
#include "jsvm/Object.h"
#endif
@@ -27,10 +27,10 @@
#include <cmath>
#include <memory>
#include <type_traits>
#include "base/HasMemberFunction.h"
#include "base/Ptr.h"
#include "base/RefCounted.h"
#include "base/memory/Memory.h"
#include "base/HasMemberFunction.h"
namespace se {
@@ -116,7 +116,7 @@ public:
explicit CCIntrusivePtrPrivateObject(const cc::IntrusivePtr<T> &p) : _ptr(p) {}
explicit CCIntrusivePtrPrivateObject(cc::IntrusivePtr<T> &&p) : _ptr(std::move(p)) {}
~CCIntrusivePtrPrivateObject() override {
if constexpr (cc::has_setScriptObject<T,void(se::Object *)>::value) {
if constexpr (cc::has_setScriptObject<T, void(se::Object *)>::value) {
_ptr->setScriptObject(nullptr);
}
}
+1 -1
View File
@@ -24,13 +24,13 @@
****************************************************************************/
#include "Value.h"
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <sstream>
#include <type_traits>
#include "Object.h"
#include <cassert>
namespace se {
+7 -7
View File
@@ -36,11 +36,11 @@
#define SCRIPT_ENGINE_JSVM 6
#ifndef SCRIPT_ENGINE_TYPE
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_NAPI
#else
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_V8
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_NAPI
#else
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_V8
#endif
#endif
#define SE_LOG_TO_JS_ENV 0 // print log to JavaScript environment, for example DevTools
@@ -65,9 +65,9 @@ CC_FORMAT_HINT(3, 4)
void selogMessage(cc::LogLevel level, const char *tag, const char *format, ...);
#if CC_DEBUG
#define SE_LOGD(...) selogMessage(cc::LogLevel::LEVEL_DEBUG, "D/", ##__VA_ARGS__)
#define SE_LOGD(...) selogMessage(cc::LogLevel::LEVEL_DEBUG, "D/", ##__VA_ARGS__)
#else
#define SE_LOGD(...)
#define SE_LOGD(...)
#endif
#define SE_LOGE(...) selogMessage(cc::LogLevel::ERR, "E/", ##__VA_ARGS__)
@@ -3,7 +3,7 @@
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "callback_queue.h"
#include "callback_queue.h"
namespace node {
@@ -11,87 +11,87 @@ template <typename R, typename... Args>
template <typename Fn>
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
CallbackQueue<R, Args...>::CreateCallback(Fn&& fn, CallbackFlags::Flags flags) {
return std::make_unique<CallbackImpl<Fn>>(std::move(fn), flags);
return std::make_unique<CallbackImpl<Fn>>(std::move(fn), flags);
}
template <typename R, typename... Args>
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
CallbackQueue<R, Args...>::Shift() {
std::unique_ptr<Callback> ret = std::move(head_);
if (ret) {
head_ = ret->get_next();
if (!head_)
tail_ = nullptr; // The queue is now empty.
size_--;
}
return ret;
std::unique_ptr<Callback> ret = std::move(head_);
if (ret) {
head_ = ret->get_next();
if (!head_)
tail_ = nullptr; // The queue is now empty.
size_--;
}
return ret;
}
template <typename R, typename... Args>
void CallbackQueue<R, Args...>::Push(std::unique_ptr<Callback> cb) {
Callback* prev_tail = tail_;
Callback* prev_tail = tail_;
size_++;
tail_ = cb.get();
if (prev_tail != nullptr)
prev_tail->set_next(std::move(cb));
else
head_ = std::move(cb);
size_++;
tail_ = cb.get();
if (prev_tail != nullptr)
prev_tail->set_next(std::move(cb));
else
head_ = std::move(cb);
}
template <typename R, typename... Args>
void CallbackQueue<R, Args...>::ConcatMove(CallbackQueue<R, Args...>&& other) {
size_ += other.size_;
if (tail_ != nullptr)
tail_->set_next(std::move(other.head_));
else
head_ = std::move(other.head_);
tail_ = other.tail_;
other.tail_ = nullptr;
other.size_ = 0;
size_ += other.size_;
if (tail_ != nullptr)
tail_->set_next(std::move(other.head_));
else
head_ = std::move(other.head_);
tail_ = other.tail_;
other.tail_ = nullptr;
other.size_ = 0;
}
template <typename R, typename... Args>
size_t CallbackQueue<R, Args...>::size() const {
return size_.load();
return size_.load();
}
template <typename R, typename... Args>
CallbackQueue<R, Args...>::Callback::Callback(CallbackFlags::Flags flags)
: flags_(flags) {}
: flags_(flags) {}
template <typename R, typename... Args>
CallbackFlags::Flags CallbackQueue<R, Args...>::Callback::flags() const {
return flags_;
return flags_;
}
template <typename R, typename... Args>
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
CallbackQueue<R, Args...>::Callback::get_next() {
return std::move(next_);
return std::move(next_);
}
template <typename R, typename... Args>
void CallbackQueue<R, Args...>::Callback::set_next(
std::unique_ptr<Callback> next) {
next_ = std::move(next);
next_ = std::move(next);
}
template <typename R, typename... Args>
template <typename Fn>
CallbackQueue<R, Args...>::CallbackImpl<Fn>::CallbackImpl(
Fn&& callback, CallbackFlags::Flags flags)
: Callback(flags),
callback_(std::move(callback)) {}
: Callback(flags),
callback_(std::move(callback)) {}
template <typename R, typename... Args>
template <typename Fn>
R CallbackQueue<R, Args...>::CallbackImpl<Fn>::Call(Args... args) {
return callback_(std::forward<Args>(args)...);
return callback_(std::forward<Args>(args)...);
}
} // namespace node
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_CALLBACK_QUEUE_INL_H_
#endif // SRC_CALLBACK_QUEUE_INL_H_
@@ -3,14 +3,14 @@
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include <atomic>
#include <atomic>
namespace node {
namespace CallbackFlags {
enum Flags {
kUnrefed = 0,
kRefed = 1,
kUnrefed = 0,
kRefed = 1,
};
}
@@ -22,57 +22,57 @@ enum Flags {
// should be run even if nothing else is keeping the event loop alive.
template <typename R, typename... Args>
class CallbackQueue {
public:
class Callback {
public:
explicit inline Callback(CallbackFlags::Flags flags);
public:
class Callback {
public:
explicit inline Callback(CallbackFlags::Flags flags);
virtual ~Callback() = default;
virtual R Call(Args... args) = 0;
virtual ~Callback() = default;
virtual R Call(Args... args) = 0;
inline CallbackFlags::Flags flags() const;
inline CallbackFlags::Flags flags() const;
private:
inline std::unique_ptr<Callback> get_next();
inline void set_next(std::unique_ptr<Callback> next);
private:
inline std::unique_ptr<Callback> get_next();
inline void set_next(std::unique_ptr<Callback> next);
CallbackFlags::Flags flags_;
std::unique_ptr<Callback> next_;
CallbackFlags::Flags flags_;
std::unique_ptr<Callback> next_;
friend class CallbackQueue;
};
friend class CallbackQueue;
};
template <typename Fn>
inline std::unique_ptr<Callback> CreateCallback(
Fn&& fn, CallbackFlags::Flags);
template <typename Fn>
inline std::unique_ptr<Callback> CreateCallback(
Fn&& fn, CallbackFlags::Flags);
inline std::unique_ptr<Callback> Shift();
inline void Push(std::unique_ptr<Callback> cb);
// ConcatMove adds elements from 'other' to the end of this list, and clears
// 'other' afterwards.
inline void ConcatMove(CallbackQueue&& other);
inline std::unique_ptr<Callback> Shift();
inline void Push(std::unique_ptr<Callback> cb);
// ConcatMove adds elements from 'other' to the end of this list, and clears
// 'other' afterwards.
inline void ConcatMove(CallbackQueue&& other);
// size() is atomic and may be called from any thread.
inline size_t size() const;
// size() is atomic and may be called from any thread.
inline size_t size() const;
private:
template <typename Fn>
class CallbackImpl final : public Callback {
public:
CallbackImpl(Fn&& callback, CallbackFlags::Flags flags);
R Call(Args... args) override;
private:
template <typename Fn>
class CallbackImpl final : public Callback {
public:
CallbackImpl(Fn&& callback, CallbackFlags::Flags flags);
R Call(Args... args) override;
private:
Fn callback_;
};
private:
Fn callback_;
};
std::atomic<size_t> size_ {0};
std::unique_ptr<Callback> head_;
Callback* tail_ = nullptr;
std::atomic<size_t> size_{0};
std::unique_ptr<Callback> head_;
Callback* tail_ = nullptr;
};
} // namespace node
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_CALLBACK_QUEUE_H_
#endif // SRC_CALLBACK_QUEUE_H_
File diff suppressed because it is too large Load Diff
@@ -24,10 +24,10 @@
#define JSVM_ARRAYSIZE(array) node::arraysize((array))
#define JSVM_FIXED_ONE_BYTE_STRING(isolate, string) \
node::FIXED_ONE_BYTE_STRING((isolate), (string))
#define JSVM_FIXED_ONE_BYTE_STRING(isolate, string) \
node::FIXED_ONE_BYTE_STRING((isolate), (string))
#define JSVM_PRIVATE_KEY(isolate, suffix) \
#define JSVM_PRIVATE_KEY(isolate, suffix) \
(v8impl::GetIsolateData(isolate)->jsvm_##suffix##_key.Get(isolate))
namespace v8impl {
@@ -38,10 +38,10 @@ using Persistent = v8::Global<T>;
using PersistentToLocal = node::PersistentToLocal;
inline void OnFatalError(const char* location,
const char* message) {
//cjh node::OnFatalError(location, message);
const char* message) {
//cjh node::OnFatalError(location, message);
}
} // end of namespace v8impl
} // end of namespace v8impl
#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_
#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_
@@ -43,42 +43,42 @@
*/
// This file needs to be compatible with C compilers.
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#include <stddef.h> // NOLINT(modernize-deprecated-headers)
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#include <stddef.h> // NOLINT(modernize-deprecated-headers)
// Use INT_MAX, this should only be consumed by the pre-processor anyway.
#define JSVM_VERSION_EXPERIMENTAL 2147483647
#ifndef JSVM_VERSION
#ifdef JSVM_EXPERIMENTAL
#define JSVM_VERSION JSVM_VERSION_EXPERIMENTAL
#else
// The baseline version for JSVM-API.
// The JSVM_VERSION controls which version will be used by default when
// compilling a native addon. If the addon developer specifically wants to use
// functions available in a new version of JSVM-API that is not yet ported in all
// LTS versions, they can set JSVM_VERSION knowing that they have specifically
// depended on that version.
#define JSVM_VERSION 8
#endif
#ifdef JSVM_EXPERIMENTAL
#define JSVM_VERSION JSVM_VERSION_EXPERIMENTAL
#else
// The baseline version for JSVM-API.
// The JSVM_VERSION controls which version will be used by default when
// compilling a native addon. If the addon developer specifically wants to use
// functions available in a new version of JSVM-API that is not yet ported in all
// LTS versions, they can set JSVM_VERSION knowing that they have specifically
// depended on that version.
#define JSVM_VERSION 8
#endif
#endif
#include "jsvm_types.h"
#ifndef JSVM_EXTERN
#ifdef _WIN32
/**
#ifdef _WIN32
/**
* @brief externally visible.
*
* @since 11
*/
#define JSVM_EXTERN __declspec(dllexport)
#elif defined(__wasm__)
#define JSVM_EXTERN \
__attribute__((visibility("default"))) \
__attribute__((__import_module__("jsvm")))
#else
#define JSVM_EXTERN __attribute__((visibility("default")))
#endif
#define JSVM_EXTERN __declspec(dllexport)
#elif defined(__wasm__)
#define JSVM_EXTERN \
__attribute__((visibility("default"))) \
__attribute__((__import_module__("jsvm")))
#else
#define JSVM_EXTERN __attribute__((visibility("default")))
#endif
#endif
/**
@@ -89,11 +89,11 @@
#define JSVM_AUTO_LENGTH SIZE_MAX
#ifdef __cplusplus
#define EXTERN_C_START extern "C" {
#define EXTERN_C_END }
#define EXTERN_C_START extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C_START
#define EXTERN_C_END
#define EXTERN_C_START
#define EXTERN_C_END
#endif
EXTERN_C_START
@@ -657,7 +657,6 @@ JSVM_EXTERN JSVM_Status OH_JSVM_GetReferenceValue(JSVM_Env env,
JSVM_EXTERN JSVM_Status OH_JSVM_CreateArray(JSVM_Env env,
JSVM_Value* result);
/**
* @brief This API returns a JSVM-API value corresponding to a JavaScript Array type. The Array's length property
* is set to the passed-in length parameter. However, the underlying buffer is not guaranteed to be pre-allocated
@@ -707,7 +706,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CreateArraybuffer(JSVM_Env env,
*/
JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLength,
JSVM_InitializedFlag initialized,
void **data);
void** data);
/**
* @brief This API release the memory of an array buffer backing store.
@@ -718,7 +717,7 @@ JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLe
* Returns {@link JSVM_INVALID_ARG } if data is null pointer.\n
* @since 12
*/
JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data);
JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void* data);
/**
* @brief This API create an array buffer using the backing store data.
@@ -738,11 +737,11 @@ JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data);
* @since 12
*/
JSVM_Status JSVM_CDECL OH_JSVM_CreateArrayBufferFromBackingStoreData(JSVM_Env env,
void *data,
void* data,
size_t backingStoreSize,
size_t offset,
size_t arrayBufferSize,
JSVM_Value *result);
JSVM_Value* result);
/**
* @brief This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification.
@@ -1850,7 +1849,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CallFunction(JSVM_Env env,
const JSVM_Value* argv,
JSVM_Value* result);
/**
/**
* @brief This API allows an add-on author to create a function object in native
* code. This is the primary mechanism to allow calling into the add-on's native
* code from JavaScript.The newly created function is not automatically visible
@@ -1876,7 +1875,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CreateFunction(JSVM_Env env,
JSVM_Callback cb,
JSVM_Value* result);
/**
/**
* @brief This method is used within a callback function to retrieve details about
* the call like the arguments and the this pointer from a given callback info.
*
@@ -2770,12 +2769,12 @@ JSVM_EXTERN JSVM_Status OH_JSVM_OpenInspectorWithName(JSVM_Env env,
* @since 12
*/
JSVM_EXTERN JSVM_Status OH_JSVM_CompileWasmModule(JSVM_Env env,
const uint8_t *wasmBytecode,
const uint8_t* wasmBytecode,
size_t wasmBytecodeLength,
const uint8_t *cacheData,
const uint8_t* cacheData,
size_t cacheDataLength,
bool *cacheRejected,
JSVM_Value *wasmModule);
bool* cacheRejected,
JSVM_Value* wasmModule);
/**
* @brief Compile the function with the specified index in the WebAssembly module
@@ -2853,4 +2852,3 @@ EXTERN_C_END
/** @} */
#endif /* ARK_RUNTIME_JSVM_JSVM_H */
@@ -42,20 +42,20 @@
* @since 11
*/
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#include <stddef.h> // NOLINT(modernize-deprecated-headers)
#include <stdint.h> // NOLINT(modernize-deprecated-headers)
#include <stdbool.h> // NOLINT(modernize-deprecated-headers)
#if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900)
typedef uint16_t char16_t;
#endif
#ifndef JSVM_CDECL
#ifdef _WIN32
#define JSVM_CDECL __cdecl
#else
#define JSVM_CDECL
#endif
#ifdef _WIN32
#define JSVM_CDECL __cdecl
#else
#define JSVM_CDECL
#endif
#endif
/**
@@ -142,7 +142,6 @@ typedef struct JSVM_CallbackInfo__* JSVM_CallbackInfo;
*/
typedef struct JSVM_Deferred__* JSVM_Deferred;
/**
* @brief Callback function pointer and data for user-provided native function which are to exposed to js via JSVM-API.
*
@@ -150,7 +149,7 @@ typedef struct JSVM_Deferred__* JSVM_Deferred;
*/
typedef struct {
JSVM_Value(JSVM_CDECL* callback)(JSVM_Env env,
JSVM_CallbackInfo info);
JSVM_CallbackInfo info);
void* data;
} JSVM_CallbackStruct;
@@ -699,12 +698,12 @@ typedef struct {
JSVM_CompileOptionId id;
/** option content. */
union {
/** ptr type. */
void *ptr;
/** int type. */
int num;
/** bool type. */
bool boolean;
/** ptr type. */
void* ptr;
/** int type. */
int num;
/** bool type. */
bool boolean;
} content;
} JSVM_CompileOptions;
@@ -715,7 +714,7 @@ typedef struct {
*/
typedef struct {
/** cache pointer. */
uint8_t *cache;
uint8_t* cache;
/** length. */
size_t length;
} JSVM_CodeCache;
@@ -751,7 +750,7 @@ typedef enum {
*/
typedef const struct {
/** profile pointer. */
int *profile;
int* profile;
/** length. */
size_t length;
} JSVM_CompileProfile;
@@ -26,50 +26,46 @@
#define NODE_MINOR_VERSION 20
#define NODE_PATCH_VERSION 1
#define NODE_VERSION_IS_LTS 1
#define NODE_VERSION_IS_LTS 1
#define NODE_VERSION_LTS_CODENAME "Hydrogen"
#define NODE_VERSION_IS_RELEASE 1
#ifndef NODE_STRINGIFY
#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
#define NODE_STRINGIFY_HELPER(n) #n
#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
#define NODE_STRINGIFY_HELPER(n) #n
#endif
#ifndef NODE_RELEASE
#define NODE_RELEASE "node"
#define NODE_RELEASE "node"
#endif
#ifndef NODE_TAG
# if NODE_VERSION_IS_RELEASE
# define NODE_TAG ""
# else
# define NODE_TAG "-pre"
# endif
#if NODE_VERSION_IS_RELEASE
#define NODE_TAG ""
#else
#define NODE_TAG "-pre"
#endif
#else
// NODE_TAG is passed without quotes when rc.exe is run from msbuild
# define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \
NODE_STRINGIFY(NODE_MINOR_VERSION) "." \
NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_STRINGIFY(NODE_TAG)
// NODE_TAG is passed without quotes when rc.exe is run from msbuild
#define NODE_EXE_VERSION \
NODE_STRINGIFY(NODE_MAJOR_VERSION) \
"." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_STRINGIFY(NODE_TAG)
#endif
# define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \
NODE_STRINGIFY(NODE_MINOR_VERSION) "." \
NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_TAG
#define NODE_VERSION_STRING \
NODE_STRINGIFY(NODE_MAJOR_VERSION) \
"." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY(NODE_PATCH_VERSION) \
NODE_TAG
#ifndef NODE_EXE_VERSION
# define NODE_EXE_VERSION NODE_VERSION_STRING
#define NODE_EXE_VERSION NODE_VERSION_STRING
#endif
#define NODE_VERSION "v" NODE_VERSION_STRING
#define NODE_VERSION_AT_LEAST(major, minor, patch) \
(( (major) < NODE_MAJOR_VERSION) \
|| ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) \
|| ((major) == NODE_MAJOR_VERSION && \
(minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION))
(((major) < NODE_MAJOR_VERSION) || ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) || ((major) == NODE_MAJOR_VERSION && (minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION))
/**
* Node.js will refuse to load modules that weren't compiled against its own
@@ -99,4 +95,4 @@
// specified. It must be always 8.
#define NODE_API_DEFAULT_MODULE_API_VERSION 8
#endif // SRC_NODE_VERSION_H_
#endif // SRC_NODE_VERSION_H_
File diff suppressed because it is too large Load Diff
+13 -13
View File
@@ -51,7 +51,7 @@ Class *Class::create(const std::string &clsName, se::Object *parent, Object *par
return cls;
}
Class* Class::create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor) {
Class *Class::create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor) {
se::AutoHandleScope scope;
se::Object *currentParent = parent;
se::Value tmp;
@@ -64,7 +64,7 @@ Class* Class::create(const std::initializer_list<const char *> &classPath, se::O
}
bool Class::init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor) {
_name = clsName;
_name = clsName;
_parent = parent;
if (_parent != nullptr)
_parent->incRef();
@@ -86,7 +86,7 @@ JSVM_Value Class::_defaultCtor(JSVM_Env env, JSVM_CallbackInfo info) {
return thisArg;
}
void Class::defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s) {
void Class::defineProperty(const char *name, JSVM_Callback g, JSVM_Callback s) {
_properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_DEFAULT_JSPROPERTY});
}
@@ -96,18 +96,18 @@ void Class::defineProperty(const std::initializer_list<const char *> &names, JSV
}
}
void Class::defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s) {
if(g != nullptr && s != nullptr)
void Class::defineStaticProperty(const char *name, JSVM_Callback g, JSVM_Callback s) {
if (g != nullptr && s != nullptr)
_properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_STATIC});
}
void Class::defineFunction(const char* name, JSVM_Callback func) {
// When JSVM defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function
void Class::defineFunction(const char *name, JSVM_Callback func) {
// When JSVM defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function
_properties.push_back({name, nullptr, func, nullptr, nullptr, nullptr, JSVM_JSPROPERTY_NO_RECEIVER_CHECK});
}
void Class::defineStaticFunction(const char* name, JSVM_Callback func) {
_properties.push_back({name, nullptr, func, nullptr, nullptr, 0, JSVM_PropertyAttributes((int)JSVM_STATIC|(int)JSVM_WRITABLE)});
void Class::defineStaticFunction(const char *name, JSVM_Callback func) {
_properties.push_back({name, nullptr, func, nullptr, nullptr, 0, JSVM_PropertyAttributes((int)JSVM_STATIC | (int)JSVM_WRITABLE)});
}
bool Class::defineStaticProperty(const char *name, const Value &v, PropertyAttribute attribute /* = PropertyAttribute::NONE */) {
@@ -129,7 +129,7 @@ JSVM_Finalize Class::_getFinalizeFunction() const {
bool Class::install() {
auto env = ScriptEngine::getEnv();
JSVM_Value cons;
JSVM_Value cons;
JSVM_Status status;
NODE_API_CALL(status, env, OH_JSVM_DefineClass(env, _name.c_str(), -1, _ctorFunc, _properties.size(), _properties.data(), &cons));
if (_parentProto) {
@@ -147,7 +147,7 @@ bool Class::install() {
_proto->root();
}
return true;
return true;
}
JSVM_Status Class::inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superProto) {
@@ -205,7 +205,7 @@ JSVM_Ref Class::_getCtorRef() const {
JSVM_Value Class::_getCtorFunc() const {
assert(_constructor);
JSVM_Value result = nullptr;
JSVM_Value result = nullptr;
JSVM_Status status;
NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_GetReferenceValue(ScriptEngine::getEnv(), _constructor, &result));
return result;
@@ -231,7 +231,7 @@ void Class::destroy() {
}
_ctor.reset();
}
OH_JSVM_DeleteReference(ScriptEngine::getEnv(), _constructor);
}
+33 -34
View File
@@ -24,11 +24,11 @@
****************************************************************************/
#pragma once
#include <string>
#include <optional>
#include <string>
#include "../Define.h"
#include "CommonHeader.h"
#include "Object.h"
#include "../Define.h"
namespace se {
class Class {
@@ -36,49 +36,48 @@ public:
static Class *create(const std::string &clsName, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
static Class *create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
void defineFunction(const char* name, JSVM_Callback func);
void defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s);
void defineProperty(const std::initializer_list<const char *> &names, JSVM_Callback g, JSVM_Callback s);
void defineFunction(const char *name, JSVM_Callback func);
void defineProperty(const char *name, JSVM_Callback g, JSVM_Callback s);
void defineProperty(const std::initializer_list<const char *> &names, JSVM_Callback g, JSVM_Callback s);
void defineStaticFunction(const char* name, JSVM_Callback func);
void defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s);
bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE);
void defineStaticFunction(const char *name, JSVM_Callback func);
void defineStaticProperty(const char *name, JSVM_Callback g, JSVM_Callback s);
bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE);
static JSVM_Value _createJSObjectWithClass(Class *cls);
void defineFinalizeFunction(JSVM_Finalize func);
static JSVM_Value _createJSObjectWithClass(Class *cls);
void defineFinalizeFunction(JSVM_Finalize func);
JSVM_Finalize _getFinalizeFunction() const;
Object * getProto() const;
bool install();
JSVM_Status inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superclass);
JSVM_Ref _getCtorRef() const;
JSVM_Value _getCtorFunc() const;
const char * getName() const { return _name.c_str(); }
static void setExports(JSVM_Value *expPtr) { _exports = expPtr; }
Object *getProto() const;
bool install();
JSVM_Status inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superclass);
JSVM_Ref _getCtorRef() const;
JSVM_Value _getCtorFunc() const;
const char *getName() const { return _name.c_str(); }
static void setExports(JSVM_Value *expPtr) { _exports = expPtr; }
static void cleanup();
// Private API used in wrapper
void _setCtor(Object *obj); // NOLINT(readability-identifier-naming)
void _setCtor(Object *obj); // NOLINT(readability-identifier-naming)
inline const std::optional<Object *> &_getCtor() const { return _ctor; } // NOLINT(readability-identifier-naming)
private:
Class();
~Class();
bool init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
void destroy();
bool init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr);
void destroy();
static JSVM_Value _defaultCtor(JSVM_Env env, JSVM_CallbackInfo info);
private:
std::optional<Object *> _ctor;
static JSVM_Value * _exports;
std::string _name;
Object * _parent = nullptr;
Object * _proto = nullptr;
Object * _parentProto = nullptr;
JSVM_CallbackStruct _ctorStruct = {Class::_defaultCtor,nullptr};
JSVM_Callback _ctorFunc = &_ctorStruct;
JSVM_Ref _constructor = nullptr;
std::vector<JSVM_PropertyDescriptor> _properties;
JSVM_Finalize _finalizeFunc = nullptr;
std::optional<Object *> _ctor;
static JSVM_Value *_exports;
std::string _name;
Object *_parent = nullptr;
Object *_proto = nullptr;
Object *_parentProto = nullptr;
JSVM_CallbackStruct _ctorStruct = {Class::_defaultCtor, nullptr};
JSVM_Callback _ctorFunc = &_ctorStruct;
JSVM_Ref _constructor = nullptr;
std::vector<JSVM_PropertyDescriptor> _properties;
JSVM_Finalize _finalizeFunc = nullptr;
};
}; // namespace se
@@ -26,9 +26,9 @@
#pragma once
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "ark_runtime/jsvm.h"
#include "ark_runtime/jsvm.h"
#else
#include "jsvm.h"
#include "jsvm.h"
#endif
#include "platform/openharmony/napi/native_common.h"
@@ -52,22 +52,22 @@
} \
} while (0)
#define NODE_API_CALL_RESULT(status, env, the_call, ret_val) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
return ret_val; \
} \
#define NODE_API_CALL_RESULT(status, env, the_call, ret_val) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
return ret_val; \
} \
} while (0)
// Returns nullptr if the_call doesn't return JSVM_OK.
#define NODE_API_CALL(status, env, the_call) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
} \
#define NODE_API_CALL(status, env, the_call) \
do { \
status = the_call; \
if (status != JSVM_OK) { \
se::internal::logJsException((env), __FILE_NAME__, __LINE__); \
} \
} while (0)
// Returns empty if the_call doesn't return JSVM_OK.
@@ -82,7 +82,7 @@
#define JSVM_CALL_BASE(theCall, retVal) \
do { \
if((theCall) != JSVM_OK){ \
if ((theCall) != JSVM_OK) { \
return retVal; \
} \
} while (0)

Some files were not shown because too many files have changed in this diff Show More