mirror of
https://github.com/cocos/cocos4.git
synced 2026-12-01 07:42:38 +08:00
Compare commits
159 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b9f9e95b9b | |||
| 7ef2d0a772 | |||
| fcdc4333b7 | |||
| 60a24625b2 | |||
| 2157fd176d | |||
| 5e627951a0 | |||
| 2c632d6dd6 | |||
| 4f6479f083 | |||
| 142c7ec6aa | |||
| 7302715a18 | |||
| 5b0b4522c0 | |||
| a803406ef1 | |||
| f570c1f02d | |||
| d0a696cfe6 | |||
| 1b3ad36e4b | |||
| ff0f46ff81 | |||
| 0616a948ef | |||
| ee89a99a9b | |||
| f620989ce7 | |||
| 661de759ef | |||
| 0ab8246486 | |||
| 67642997f7 | |||
| 3be9ebc5b7 | |||
| 47ebc462e5 | |||
| b4bea55859 | |||
| 82f13c86e9 | |||
| 0fd910220e | |||
| 557b06f7e6 | |||
| b46553e615 | |||
| fffd9a514a | |||
| 5678d0d17c | |||
| 2ce7b89be5 | |||
| 6b455561f4 | |||
| 60f9352c56 | |||
| f66365f959 | |||
| a3c3fcbea5 | |||
| 2a75cfb9da | |||
| 0c3f4534b8 | |||
| 7f806abad6 | |||
| df98a99bb6 | |||
| a5090e5ae4 | |||
| 3b71bf6935 | |||
| 54fd070848 | |||
| 6722aac669 | |||
| 68552314c0 | |||
| 550eb15641 | |||
| c438c2d3f8 | |||
| f5eaf97ce7 | |||
| 69d3d6033a | |||
| 469614cf0b | |||
| f81094f226 | |||
| 825362fac1 | |||
| 609512f8da | |||
| 09b63786f4 | |||
| 2b7b438768 | |||
| 6b5c8556a2 | |||
| ff436d6a27 | |||
| 09c38ea03f | |||
| 926bd5b619 | |||
| e317c04512 | |||
| 140068ddb1 | |||
| 80a9d0619e | |||
| a01046e391 | |||
| 2b6ec3b4f0 | |||
| 6060f58d1a | |||
| 18456b6706 | |||
| 62b55a0c48 | |||
| 0eac18be1a | |||
| 01983b75f2 | |||
| 2d003cc616 | |||
| b710cb6e9b | |||
| f948b5900e | |||
| b7883f18ba | |||
| 3ab299035a | |||
| c2ab919e9d | |||
| 5690d1b8a5 | |||
| ed0751652b | |||
| 97e402c3dc | |||
| f378a866cb | |||
| 7253ee4a7f | |||
| db5462603e | |||
| 9f0e30acb3 | |||
| a0a2e97c00 | |||
| 90e551b4a1 | |||
| 0a21bb9397 | |||
| 2c91155928 | |||
| 6f90cec3d4 | |||
| 4992692780 | |||
| d5f24e6170 | |||
| e778833d15 | |||
| c3a8a72f63 | |||
| 2c0e75059f | |||
| 19f4bd5b16 | |||
| 085d05928d | |||
| fb4d586629 | |||
| 620d38cf42 | |||
| d2713fe00e | |||
| 3aeb193d42 | |||
| c4e4790ee6 | |||
| 143af30cf2 | |||
| d6ff23fed4 | |||
| 84e8d4ebf7 | |||
| f2b9936033 | |||
| 129eb437ad | |||
| c58c893334 | |||
| ab982aec68 | |||
| 2d2bbe6731 | |||
| 187387b03f | |||
| 661253a521 | |||
| b6d0f02e88 | |||
| dd1b155d3a | |||
| df96ee85f3 | |||
| 708a343ce8 | |||
| 393203c2f8 | |||
| f3d11f017b | |||
| 09c201017c | |||
| ce6107d930 | |||
| ab8792686b | |||
| 44ef76855b | |||
| 8878e7aade | |||
| 621880a123 | |||
| 2eb268bf9a | |||
| 2e6cc9b127 | |||
| 98917ff2a7 | |||
| dc29d2f8f8 | |||
| eec2a1693b | |||
| 632f9b442f | |||
| 8ce19b658e | |||
| 07f2c5fb43 | |||
| 9b17fd6165 | |||
| e2795f9ecd | |||
| 89a412e0d6 | |||
| aef31099d8 | |||
| 89f8768e57 | |||
| 424be5d0b2 | |||
| e5183b796a | |||
| 32478c1a9c | |||
| 74e632a3d6 | |||
| 26883ba6f4 | |||
| 055c70f8d2 | |||
| 99f6db401c | |||
| 9390ee6bc0 | |||
| 7f258dac58 | |||
| 5c99570616 | |||
| 821928733b | |||
| f567861ff6 | |||
| a7a20b64ab | |||
| 7c75834010 | |||
| 8fd985af75 | |||
| cc97bc8af4 | |||
| 92124590fe | |||
| 822ac6026c | |||
| 4a6f83bd6d | |||
| 04f063eb2b | |||
| 910865bd8b | |||
| e384f54ed2 | |||
| 5964835c83 | |||
| f4ae16247c | |||
| 4b4a3ca13f |
@@ -20,8 +20,14 @@ if ($env:GITHUB_BASE_REF) {
|
|||||||
# Push
|
# Push
|
||||||
$gitHubEvent = Get-Content $env:GITHUB_EVENT_PATH | ConvertFrom-Json
|
$gitHubEvent = Get-Content $env:GITHUB_EVENT_PATH | ConvertFrom-Json
|
||||||
Write-Host "GitHub event: $gitHubEvent"
|
Write-Host "GitHub event: $gitHubEvent"
|
||||||
git fetch origin $gitHubEvent.before --depth=1
|
$beforeSha = $gitHubEvent.before
|
||||||
$diffFiles = git diff --name-only --diff-filter=$diffFilter $gitHubEvent.before $env:GITHUB_SHA
|
# 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"
|
Write-Host "Diff files: $diffFiles"
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
token: ${{ github.token }}
|
token: ${{ github.token }}
|
||||||
ref: ${{ github.head_sha }}
|
ref: ${{ github.head_sha }}
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
- id: get_change_files
|
- id: get_change_files
|
||||||
uses: fish9167/file-changes-action@v1.2.3
|
uses: fish9167/file-changes-action@v1.2.3
|
||||||
@@ -25,18 +26,13 @@ jobs:
|
|||||||
output: ' '
|
output: ' '
|
||||||
fileOutput: ' '
|
fileOutput: ' '
|
||||||
|
|
||||||
- name: Echo change files
|
- uses: DoozyX/clang-format-lint-action@v0.18
|
||||||
run: |
|
|
||||||
cat $HOME/files.txt
|
|
||||||
mv $HOME/files.txt ${{github.workspace}}/files.txt
|
|
||||||
|
|
||||||
- uses: fish9167/clang-format-lint-action@master
|
|
||||||
with:
|
with:
|
||||||
source: ./native
|
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'
|
extensions: 'c,h,hpp,cpp,cxx'
|
||||||
style: file
|
style: file
|
||||||
inplace: True
|
inplace: true
|
||||||
clangFormatVersion: 12
|
clangFormatVersion: 12
|
||||||
|
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
|
|||||||
@@ -483,8 +483,8 @@ jobs:
|
|||||||
echo "set(CC_USE_GLES3 OFF)" >> build-mac/proj/cfg.cmake
|
echo "set(CC_USE_GLES3 OFF)" >> build-mac/proj/cfg.cmake
|
||||||
echo "set(CC_USE_METAL ON)" >> build-mac/proj/cfg.cmake
|
echo "set(CC_USE_METAL ON)" >> build-mac/proj/cfg.cmake
|
||||||
# Test JSVM v8 backend on macOS.
|
# Test JSVM v8 backend on macOS.
|
||||||
echo "set(USE_SE_V8 OFF)" >> build-mac/proj/cfg.cmake
|
echo "set(USE_SE_V8 ON)" >> build-mac/proj/cfg.cmake
|
||||||
echo "set(USE_SE_JSVM 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(USE_WEBSOCKET_SERVER OFF)" >> build-mac/proj/cfg.cmake
|
||||||
echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> 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
|
echo "set(CC_EXECUTABLE_NAME \"\")" >> build-mac/proj/cfg.cmake
|
||||||
@@ -493,7 +493,6 @@ jobs:
|
|||||||
RES_DIR=$GITHUB_WORKSPACE/templates/mac/build-mac
|
RES_DIR=$GITHUB_WORKSPACE/templates/mac/build-mac
|
||||||
cd build-mac
|
cd build-mac
|
||||||
cmake ../ -GXcode -DCMAKE_OSX_ARCHITECTURES=${{ matrix.config.arch }} -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$NATIVE_ROOT
|
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 }}
|
cmake --build . --config Release -- -jobs $NUM_OF_CORES -arch ${{ matrix.config.arch }}
|
||||||
echo "Compile MacOSX Release Done!"
|
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_VULKAN OFF)" >> build-ios/proj/cfg.cmake
|
||||||
echo "set(CC_USE_GLES2 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(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_WEBSOCKET_SERVER OFF)" >> build-ios/proj/cfg.cmake
|
||||||
echo "set(USE_DRAGONBONES 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
|
echo "set(CMAKE_CXX_STANDARD_REQUIRED OFF)" >> build-ios/proj/cfg.cmake
|
||||||
@@ -548,7 +547,6 @@ jobs:
|
|||||||
-DCMAKE_OSX_ARCHITECTURES=${{ matrix.config.arch }} \
|
-DCMAKE_OSX_ARCHITECTURES=${{ matrix.config.arch }} \
|
||||||
-DRES_DIR=$RES_DIR \
|
-DRES_DIR=$RES_DIR \
|
||||||
-DCOCOS_X_PATH=$NATIVE_ROOT
|
-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 -- -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
|
cmake --build . --config Debug -- -jobs $NUM_OF_CORES CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO
|
||||||
echo "Compile iOS Done!"
|
echo "Compile iOS Done!"
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: ${{ matrix.node-version }}
|
node-version: ${{ matrix.node-version }}
|
||||||
- run: npm ci --ignore-scripts
|
- run: npm ci --ignore-scripts
|
||||||
|
- run: node scripts/spread-pal.cjs
|
||||||
- run: npm run build:debug-infos
|
- run: npm run build:debug-infos
|
||||||
- name: Download external
|
- name: Download external
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -46,3 +46,11 @@ platforms/runtime/platforms/vivo-mini-game/ral.min.js
|
|||||||
@types/consts.d.ts
|
@types/consts.d.ts
|
||||||
|
|
||||||
__TS_ENGINE__/
|
__TS_ENGINE__/
|
||||||
|
|
||||||
|
# pal 由 @cocos/engine-pal 在 postinstall 挂载(软链/复制),不入库
|
||||||
|
/pal
|
||||||
|
|
||||||
|
# platforms 源码已抽到 @cocos/engine-platforms;其预打包 adapter 由 postinstall 的
|
||||||
|
# spread-adapter.cjs 复制到 bin/adapter(/bin 已忽略)。platforms 源码不再入库。
|
||||||
|
/platforms
|
||||||
|
|
||||||
|
|||||||
Vendored
+83
@@ -37,6 +37,38 @@ declare module 'pal/minigame' {
|
|||||||
getSharedCanvas(): any;
|
getSharedCanvas(): any;
|
||||||
getOpenDataContext(): any;
|
getOpenDataContext(): any;
|
||||||
|
|
||||||
|
// worker
|
||||||
|
/**
|
||||||
|
* Create a worker thread from a packaged script path.
|
||||||
|
*
|
||||||
|
* IMPORTANT — this is optional and genuinely absent on some platforms:
|
||||||
|
* - Present: WeChat (`wx.createWorker`), ByteDance (`tt.createWorker`), Alipay
|
||||||
|
* (`my.createWorker`), Baidu (`swan.createWorker`, base library 1.6.1+), and the
|
||||||
|
* quick-game family (`qg.createWorker` on Xiaomi / Huawei 1117+ / OPPO / vivo).
|
||||||
|
* Each `pal/minigame/*.js` adapter starts with `cloneObject(minigame, <platformGlobal>)`,
|
||||||
|
* and `cloneObject` copies functions with `.bind(origin)` — so `createWorker` arrives on
|
||||||
|
* `minigame` for free, already bound to the right global. No per-platform adapter code
|
||||||
|
* is needed, and `pal/` itself must not be edited (it is regenerated from the
|
||||||
|
* `@cocos/engine-pal` package on postinstall).
|
||||||
|
* - Absent: Taobao mini-game has NO worker API at all (its API surface has no Worker
|
||||||
|
* category), and no `Worker` / `Blob` / `URL.createObjectURL` either — there is no way to
|
||||||
|
* get a real thread there. Callers must degrade to synchronous execution.
|
||||||
|
*
|
||||||
|
* Returns `undefined` (rather than throwing) when creation fails on Huawei quick game, so
|
||||||
|
* the result MUST be null-checked.
|
||||||
|
*
|
||||||
|
* Every platform caps concurrency at ONE worker except WeChat V2 (standard worker).
|
||||||
|
* Script paths must be relative (no leading "/") and end with ".js", and the file must be
|
||||||
|
* packaged under the workers directory declared in game.json / manifest.json / app.json.
|
||||||
|
*/
|
||||||
|
createWorker?: (scriptPath: string, options?: MinigameWorkerOptions) => MinigameWorker | undefined;
|
||||||
|
/**
|
||||||
|
* Platform environment info. On WeChat this carries `isSupportStandardWorker`, which gates
|
||||||
|
* the V2 standard worker (grey release; NOT supported in the WeChat devtools). Absent on
|
||||||
|
* platforms whose global has no `env`.
|
||||||
|
*/
|
||||||
|
env?: MinigameEnv;
|
||||||
|
|
||||||
// file system
|
// file system
|
||||||
getFileSystemManager(): FileSystemManager;
|
getFileSystemManager(): FileSystemManager;
|
||||||
loadSubpackage? (option: LoadSubpackageOption): LoadSubpackageTask;
|
loadSubpackage? (option: LoadSubpackageOption): LoadSubpackageTask;
|
||||||
@@ -133,6 +165,57 @@ declare module 'pal/minigame' {
|
|||||||
getAudioContext?: () => AudioContext;
|
getAudioContext?: () => AudioContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Options accepted by `minigame.createWorker`. Only WeChat defines any; other platforms ignore
|
||||||
|
* the second argument. Kept loose on purpose — the platform surface differs and grows.
|
||||||
|
*/
|
||||||
|
export interface MinigameWorkerOptions {
|
||||||
|
/**
|
||||||
|
* WeChat only, base library 2.13.0+. Uses the "experimental" worker implementation, which
|
||||||
|
* speeds up JS execution several times over on iOS. Requires pairing with
|
||||||
|
* `onProcessKilled`, because the system may reclaim the worker process at any time.
|
||||||
|
* This legacy option does not select the V2 standard Worker.
|
||||||
|
*/
|
||||||
|
useExperimentalWorker?: boolean;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Platform environment info exposed as `minigame.env`.
|
||||||
|
*/
|
||||||
|
export interface MinigameEnv {
|
||||||
|
/**
|
||||||
|
* WeChat only. `true` when the runtime supports the V2 standard worker: multiple concurrent
|
||||||
|
* workers, `SharedArrayBuffer`, transfer lists in `postMessage`, `OffscreenCanvas`. Requires
|
||||||
|
* WeChat client >= 8.0.74 (Android) and base library >= 3.17.0, is in grey release, and is
|
||||||
|
* NOT supported in the WeChat devtools — so it must be checked at runtime, never assumed.
|
||||||
|
*/
|
||||||
|
isSupportStandardWorker?: boolean;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The worker handle returned by `minigame.createWorker`. The API shape is remarkably consistent
|
||||||
|
* across WeChat / ByteDance / Alipay / Baidu / quick-game: all use `postMessage` + `onMessage`,
|
||||||
|
* and all expose the worker-side global as `worker` (NOT `self`).
|
||||||
|
*
|
||||||
|
* Differences that the engine's backend layer must absorb:
|
||||||
|
* - `onError` is missing on some platforms (Huawei quick game documents only
|
||||||
|
* create/postMessage/onMessage/terminate) — guard before calling.
|
||||||
|
* - `onProcessKilled` is WeChat-only (iOS experimental worker reclamation).
|
||||||
|
* - The transfer list (second `postMessage` argument) is honored ONLY by WeChat V2. Huawei quick
|
||||||
|
* game documents data transfer as structured clone with no transferable objects; passing a
|
||||||
|
* transfer list elsewhere may throw, so omit it unless the platform supports it.
|
||||||
|
*/
|
||||||
|
export interface MinigameWorker {
|
||||||
|
postMessage(message: any, transfer?: any[]): void;
|
||||||
|
onMessage(listener: (res: any) => void): void;
|
||||||
|
onError?: (listener: (err: any) => void) => void;
|
||||||
|
terminate(): void;
|
||||||
|
/** WeChat only: fired when the system reclaims the worker process. */
|
||||||
|
onProcessKilled?: (listener: (err: any) => void) => void;
|
||||||
|
}
|
||||||
|
|
||||||
export type AccelerometerIntervalMode = 'game' | 'ui' | 'normal';
|
export type AccelerometerIntervalMode = 'game' | 'ui' | 'normal';
|
||||||
|
|
||||||
export interface AccelerometerStartParameter {
|
export interface AccelerometerStartParameter {
|
||||||
|
|||||||
Vendored
+12
@@ -22,6 +22,12 @@ declare module 'pal/screen-adapter' {
|
|||||||
* Determine whether use headless renderer, which means do not support some screen operations.
|
* Determine whether use headless renderer, which means do not support some screen operations.
|
||||||
*/
|
*/
|
||||||
isHeadlessMode: boolean;
|
isHeadlessMode: boolean;
|
||||||
|
/**
|
||||||
|
* Optional startup DPR cap, currently consumed by Web.
|
||||||
|
* Supporting adapters validate that it is finite and >= 1; other adapters ignore it.
|
||||||
|
* Omission/null preserves the adapter's default policy (Web caps DPR at 2).
|
||||||
|
*/
|
||||||
|
maxDevicePixelRatio?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
class ScreenAdapter {
|
class ScreenAdapter {
|
||||||
@@ -58,6 +64,12 @@ declare module 'pal/screen-adapter' {
|
|||||||
* Query the current fullscreen state.
|
* Query the current fullscreen state.
|
||||||
*/
|
*/
|
||||||
public get isFullScreen (): boolean;
|
public get isFullScreen (): boolean;
|
||||||
|
/**
|
||||||
|
* Optional capability: the applied startup cap, or null for the adapter's default.
|
||||||
|
* Adapters exposing this property consume and validate maxDevicePixelRatio.
|
||||||
|
* Absent on adapters that ignore this setting.
|
||||||
|
*/
|
||||||
|
public readonly maxDevicePixelRatio?: number | null;
|
||||||
/**
|
/**
|
||||||
* The ratio of pixel sizes:
|
* The ratio of pixel sizes:
|
||||||
* the size of one CSS pixel to the size of one physical pixel.
|
* the size of one CSS pixel to the size of one physical pixel.
|
||||||
|
|||||||
Vendored
+61
@@ -0,0 +1,61 @@
|
|||||||
|
/**
|
||||||
|
* Engine-side contract of the `pal/worker` module.
|
||||||
|
*
|
||||||
|
* Self-contained on purpose: type checking, IDE services and declaration builds must not depend on
|
||||||
|
* whether the installed PAL package ships a worker module. When `pal/worker` is absent (an older
|
||||||
|
* PAL, or the single-thread compatibility module which is JS only), TypeScript resolves the import to
|
||||||
|
* this ambient declaration. `tests/scripts/pal-worker-types.test.cjs` checks that a real PAL
|
||||||
|
* `worker/type.d.ts` stays structurally identical to these interfaces.
|
||||||
|
*/
|
||||||
|
declare module 'pal/worker' {
|
||||||
|
export interface IWorker {
|
||||||
|
postMessage (message: any, transfer?: Transferable[]): void;
|
||||||
|
onMessage (listener: (res: any) => void): void;
|
||||||
|
onError (listener: (err: any) => void): void;
|
||||||
|
terminate (): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IWorkerDiagnosis {
|
||||||
|
ready: boolean;
|
||||||
|
version: 0 | 1 | 2;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IWorkerBackend {
|
||||||
|
readonly concurrencyLimit: number;
|
||||||
|
readonly supportsTransfer: boolean;
|
||||||
|
readonly supportsSharedArrayBuffer: boolean;
|
||||||
|
readonly supportsFunctionWorker: boolean;
|
||||||
|
readonly capabilityReason: string;
|
||||||
|
createScriptWorker (path: string): IWorker;
|
||||||
|
diagnose (path: string): IWorkerDiagnosis;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IPlatformWorkerBackend extends IWorkerBackend {
|
||||||
|
readonly supportsStandardWorker: boolean;
|
||||||
|
readonly scriptFailureHint: string;
|
||||||
|
resolveScriptWorker (path: string): IWorkerResolution;
|
||||||
|
readonly hardwareConcurrency: number;
|
||||||
|
readonly scriptFallback: IPlatformWorkerBackend | null;
|
||||||
|
createFunctionWorker (fn: (...args: any[]) => any): IWorker | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IWorkerResolution {
|
||||||
|
backend: IPlatformWorkerBackend | null;
|
||||||
|
diagnosis: IWorkerDiagnosis;
|
||||||
|
warnOnFailure: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IWorkerCapabilities {
|
||||||
|
supportsStandardWorker: boolean;
|
||||||
|
available: boolean;
|
||||||
|
parallel: boolean;
|
||||||
|
concurrencyLimit: number;
|
||||||
|
supportsTransfer: boolean;
|
||||||
|
supportsSharedArrayBuffer: boolean;
|
||||||
|
supportsFunctionWorker: boolean;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createWorkerBackend (): IPlatformWorkerBackend;
|
||||||
|
}
|
||||||
@@ -3226,6 +3226,18 @@ Cannot access game frame or container.
|
|||||||
|
|
||||||
Setting window size is not supported.
|
Setting window size is not supported.
|
||||||
|
|
||||||
|
### 9204
|
||||||
|
|
||||||
|
maxDevicePixelRatio, when specified, must be a finite number >= 1.
|
||||||
|
|
||||||
|
### 9205
|
||||||
|
|
||||||
|
PAL did not apply the configured maximum DPR. Check that the engine and PAL versions match.
|
||||||
|
|
||||||
|
### 9206
|
||||||
|
|
||||||
|
maxDevicePixelRatio cannot change after ScreenAdapter.init().
|
||||||
|
|
||||||
### 9300
|
### 9300
|
||||||
|
|
||||||
The current buffer beyond the limit in ui static component, please reduce the amount
|
The current buffer beyond the limit in ui static component, please reduce the amount
|
||||||
@@ -3980,3 +3992,75 @@ Debug bones or slots is invalid in cached mode.
|
|||||||
### 16419
|
### 16419
|
||||||
|
|
||||||
Spine version not supported.
|
Spine version not supported.
|
||||||
|
|
||||||
|
### 16420
|
||||||
|
|
||||||
|
End time must bigger than start time.
|
||||||
|
|
||||||
|
### 16500
|
||||||
|
|
||||||
|
WorkerPool script path must be a non-empty string
|
||||||
|
|
||||||
|
### 16501
|
||||||
|
|
||||||
|
WorkerPool requires a self-contained task function or a worker script path
|
||||||
|
|
||||||
|
### 16502
|
||||||
|
|
||||||
|
WorkerPool has been terminated
|
||||||
|
|
||||||
|
### 16503
|
||||||
|
|
||||||
|
WorkerPool has no available execution backend
|
||||||
|
|
||||||
|
### 16504
|
||||||
|
|
||||||
|
No worker backend for "%s" (%s). Provide options.fallback to run single-threaded, or fix packaging (docs/worker/README.md).
|
||||||
|
|
||||||
|
### 16505
|
||||||
|
|
||||||
|
WorkerPool degraded to single-threaded for "%s": worker backend failed (%s). %s
|
||||||
|
|
||||||
|
### 16506
|
||||||
|
|
||||||
|
WorkerPool is rejecting tasks (no options.fallback) for "%s": worker backend failed (%s). %s
|
||||||
|
|
||||||
|
### 16507
|
||||||
|
|
||||||
|
WorkerPool could not use a worker for "%s" and is running single-threaded via options.fallback. Reason: %s. %s
|
||||||
|
|
||||||
|
### 16508
|
||||||
|
|
||||||
|
WorkerPool could not use a worker for "%s" and is REJECTING tasks (no options.fallback). Reason: %s. %s
|
||||||
|
|
||||||
|
### 16509
|
||||||
|
|
||||||
|
Worker error
|
||||||
|
|
||||||
|
### 16510
|
||||||
|
|
||||||
|
Worker is unavailable and no synchronous fallback exists
|
||||||
|
|
||||||
|
### 16511
|
||||||
|
|
||||||
|
Worker task timed out after %sms — the worker never replied (deadlock, infinite loop, or non-protocol script). Worker discarded; see docs/worker/README.md
|
||||||
|
|
||||||
|
### 16512
|
||||||
|
|
||||||
|
Worker has been disposed
|
||||||
|
|
||||||
|
### 16513
|
||||||
|
|
||||||
|
Worker script sent a malformed reply — it must implement the engine protocol: receive { id, args }, post back { id, ok, value } or { id, ok: false, error } (docs/worker/cc-worker-template.js)
|
||||||
|
|
||||||
|
### 16514
|
||||||
|
|
||||||
|
Worker task failed
|
||||||
|
|
||||||
|
### 16515
|
||||||
|
|
||||||
|
createWorker(path) requires a non-empty worker script path
|
||||||
|
|
||||||
|
### 16516
|
||||||
|
|
||||||
|
Function workers are unavailable; use WorkerPool for an automatic sync fallback, or createWorker(path) (mode 2).
|
||||||
|
|||||||
+66
-46
@@ -300,6 +300,13 @@
|
|||||||
"overrideConstants": {
|
"overrideConstants": {
|
||||||
"CULL_MESHOPT": false
|
"CULL_MESHOPT": false
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"worker": {
|
||||||
|
"modules": ["worker"]
|
||||||
|
},
|
||||||
|
"worker-pool": {
|
||||||
|
"modules": ["worker", "worker-pool"],
|
||||||
|
"dependentModules": ["worker"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"moduleOverrides": [{
|
"moduleOverrides": [{
|
||||||
@@ -382,70 +389,75 @@
|
|||||||
"test": "context.buildTimeConstants && context.buildTimeConstants.HTML5",
|
"test": "context.buildTimeConstants && context.buildTimeConstants.HTML5",
|
||||||
"isVirtualModule": true,
|
"isVirtualModule": true,
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"pal/minigame": "pal/minigame/non-minigame.ts",
|
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||||
"pal/audio": "pal/audio/web/player.ts",
|
"pal/worker": "pal/worker/web/index.js",
|
||||||
"pal/system-info": "pal/system-info/web/system-info.ts",
|
"pal/audio": "pal/audio/web/player.js",
|
||||||
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.ts",
|
"pal/system-info": "pal/system-info/web/system-info.js",
|
||||||
"pal/input": "pal/input/web/index.ts",
|
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.js",
|
||||||
"pal/env": "pal/env/web/env.ts",
|
"pal/input": "pal/input/web/index.js",
|
||||||
"pal/pacer": "pal/pacer/pacer-web.ts",
|
"pal/env": "pal/env/web/env.js",
|
||||||
"pal/wasm": "pal/wasm/wasm-web.ts"
|
"pal/pacer": "pal/pacer/pacer-web.js",
|
||||||
|
"pal/wasm": "pal/wasm/wasm-web.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"test": "context.buildTimeConstants && context.buildTimeConstants.NATIVE",
|
"test": "context.buildTimeConstants && context.buildTimeConstants.NATIVE",
|
||||||
"isVirtualModule": true,
|
"isVirtualModule": true,
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"pal/minigame": "pal/minigame/non-minigame.ts",
|
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||||
"pal/audio": "pal/audio/native/player.ts",
|
"pal/worker": "pal/worker/native/index.js",
|
||||||
"pal/system-info": "pal/system-info/native/system-info.ts",
|
"pal/audio": "pal/audio/native/player.js",
|
||||||
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.ts",
|
"pal/system-info": "pal/system-info/native/system-info.js",
|
||||||
"pal/input": "pal/input/native/index.ts",
|
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.js",
|
||||||
"pal/env": "pal/env/native/env.ts",
|
"pal/input": "pal/input/native/index.js",
|
||||||
"pal/pacer": "pal/pacer/pacer-native.ts",
|
"pal/env": "pal/env/native/env.js",
|
||||||
"pal/wasm": "pal/wasm/wasm-native.ts"
|
"pal/pacer": "pal/pacer/pacer-native.js",
|
||||||
|
"pal/wasm": "pal/wasm/wasm-native.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"test": "context.buildTimeConstants && context.buildTimeConstants.MINIGAME",
|
"test": "context.buildTimeConstants && context.buildTimeConstants.MINIGAME",
|
||||||
"isVirtualModule": true,
|
"isVirtualModule": true,
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.ts",
|
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.js",
|
||||||
"pal/audio": "pal/audio/minigame/player.ts",
|
"pal/worker": "pal/worker/minigame/index.js",
|
||||||
"pal/system-info": "pal/system-info/minigame/system-info.ts",
|
"pal/audio": "pal/audio/minigame/player.js",
|
||||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
|
"pal/system-info": "pal/system-info/minigame/system-info.js",
|
||||||
"pal/input": "pal/input/minigame/index.ts",
|
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
|
||||||
"pal/env": "pal/env/minigame/env.ts",
|
"pal/input": "pal/input/minigame/index.js",
|
||||||
"pal/pacer": "pal/pacer/pacer-minigame.ts",
|
"pal/env": "pal/env/minigame/env.js",
|
||||||
"pal/wasm": "pal/wasm/wasm-minigame.ts"
|
"pal/pacer": "pal/pacer/pacer-minigame.js",
|
||||||
|
"pal/wasm": "pal/wasm/wasm-minigame.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"test": "context.buildTimeConstants && context.buildTimeConstants.RUNTIME_BASED",
|
"test": "context.buildTimeConstants && context.buildTimeConstants.RUNTIME_BASED",
|
||||||
"isVirtualModule": true,
|
"isVirtualModule": true,
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"pal/minigame": "pal/minigame/runtime.ts",
|
"pal/minigame": "pal/minigame/runtime.js",
|
||||||
"pal/audio": "pal/audio/minigame/player.ts",
|
"pal/worker": "pal/worker/minigame/index.js",
|
||||||
"pal/system-info": "pal/system-info/minigame/system-info.ts",
|
"pal/audio": "pal/audio/minigame/player.js",
|
||||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
|
"pal/system-info": "pal/system-info/minigame/system-info.js",
|
||||||
"pal/input": "pal/input/minigame/index.ts",
|
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
|
||||||
"pal/env": "pal/env/runtime/env.ts",
|
"pal/input": "pal/input/minigame/index.js",
|
||||||
"pal/pacer": "pal/pacer/pacer-minigame.ts",
|
"pal/env": "pal/env/runtime/env.js",
|
||||||
"pal/wasm": "pal/wasm/wasm-minigame.ts"
|
"pal/pacer": "pal/pacer/pacer-minigame.js",
|
||||||
|
"pal/wasm": "pal/wasm/wasm-minigame.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"test": "context.buildTimeConstants && context.buildTimeConstants.NODEJS",
|
"test": "context.buildTimeConstants && context.buildTimeConstants.NODEJS",
|
||||||
"isVirtualModule": true,
|
"isVirtualModule": true,
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"pal/minigame": "pal/minigame/non-minigame.ts",
|
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||||
"pal/audio": "pal/audio/nodejs/player.ts",
|
"pal/worker": "pal/worker/nodejs/index.js",
|
||||||
"pal/system-info": "pal/system-info/nodejs/system-info.ts",
|
"pal/audio": "pal/audio/nodejs/player.js",
|
||||||
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.ts",
|
"pal/system-info": "pal/system-info/nodejs/system-info.js",
|
||||||
"pal/input": "pal/input/nodejs/index.ts",
|
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.js",
|
||||||
"pal/env": "pal/env/nodejs/env.ts",
|
"pal/input": "pal/input/nodejs/index.js",
|
||||||
"pal/pacer": "pal/pacer/pacer-nodejs.ts",
|
"pal/env": "pal/env/nodejs/env.js",
|
||||||
"pal/wasm": "pal/wasm/wasm-nodejs.ts"
|
"pal/pacer": "pal/pacer/pacer-nodejs.js",
|
||||||
|
"pal/wasm": "pal/wasm/wasm-nodejs.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -470,7 +482,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"test": "context.buildTimeConstants.SPINE_3_8",
|
"test": "context.buildTimeConstants.SPINE_3_8 && context.buildTimeConstants.SPINE_4_2",
|
||||||
|
"isVirtualModule": false,
|
||||||
|
"overrides": {
|
||||||
|
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-dynamic.ts",
|
||||||
|
"cocos/spine/lib/spine-instantiate.ts": "cocos/spine/lib/spine-instantiate-dynamic.ts"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"test": "context.buildTimeConstants.SPINE_3_8 && !context.buildTimeConstants.SPINE_4_2",
|
||||||
"isVirtualModule": false,
|
"isVirtualModule": false,
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-3.8.ts",
|
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-3.8.ts",
|
||||||
@@ -478,7 +498,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"test": "context.buildTimeConstants.SPINE_4_2",
|
"test": "context.buildTimeConstants.SPINE_4_2 && !context.buildTimeConstants.SPINE_3_8",
|
||||||
"isVirtualModule": false,
|
"isVirtualModule": false,
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-4.2.ts",
|
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-4.2.ts",
|
||||||
@@ -877,10 +897,10 @@
|
|||||||
"cocos/asset/asset-manager/weak-cache.ts",
|
"cocos/asset/asset-manager/weak-cache.ts",
|
||||||
"cocos/2d/framework/ui-skew-utils.ts",
|
"cocos/2d/framework/ui-skew-utils.ts",
|
||||||
"cocos/spine/lib/spine-binary.ts",
|
"cocos/spine/lib/spine-binary.ts",
|
||||||
"pal/input/minigame/gamepad-input.ts",
|
"pal/input/minigame/gamepad-input.js",
|
||||||
"pal/input/minigame/handheld-input.ts",
|
"pal/input/minigame/handheld-input.js",
|
||||||
"pal/input/minigame/handle-input.ts",
|
"pal/input/minigame/handle-input.js",
|
||||||
"pal/input/minigame/hmd-input.ts"
|
"pal/input/minigame/hmd-input.js"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd.
|
||||||
|
|
||||||
https://www.cocos.com/
|
http://www.cocos.com
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
@@ -22,15 +22,11 @@
|
|||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
// Vertex/index capacity limits of the graphics geometry.
|
||||||
|
|
||||||
export * from './accelerometer-input';
|
// Uint16 can address 65536 vertices (indices 0-65535), and a single fill()/stroke() batch is not
|
||||||
export * from './gamepad-input';
|
// split, so the buffers have to cover this count.
|
||||||
export * from './handle-input';
|
export const MAX_VERTEX_COUNT = 65536;
|
||||||
export * from './hmd-input';
|
// Fill and stroke both emit at most 3 indices per vertex, see GraphicsAssembler.
|
||||||
export * from './handheld-input';
|
export const INDICES_PER_VERTEX = 3;
|
||||||
export * from './keyboard-input';
|
export const MAX_INDEX_COUNT = MAX_VERTEX_COUNT * INDICES_PER_VERTEX;
|
||||||
export * from './mouse-input';
|
|
||||||
export * from './touch-input';
|
|
||||||
|
|
||||||
checkPalIntegrity<typeof import('pal/input')>(withImpl<typeof import('./index')>());
|
|
||||||
@@ -28,12 +28,10 @@ import { MeshRenderData } from '../../../renderer/render-data';
|
|||||||
import { IBatcher } from '../../../renderer/i-batcher';
|
import { IBatcher } from '../../../renderer/i-batcher';
|
||||||
import { Graphics } from '../../../components/graphics';
|
import { Graphics } from '../../../components/graphics';
|
||||||
import { LineCap, LineJoin, PointFlags } from '../types';
|
import { LineCap, LineJoin, PointFlags } from '../types';
|
||||||
|
import { MAX_VERTEX_COUNT, INDICES_PER_VERTEX } from '../constants';
|
||||||
import { earcut as Earcut } from './earcut';
|
import { earcut as Earcut } from './earcut';
|
||||||
import { Impl, Point } from './impl';
|
import { Impl, Point } from './impl';
|
||||||
|
|
||||||
const MAX_VERTEX = 65535;
|
|
||||||
const MAX_INDICES = MAX_VERTEX * 2;
|
|
||||||
|
|
||||||
const PI = Math.PI;
|
const PI = Math.PI;
|
||||||
const min = Math.min;
|
const min = Math.min;
|
||||||
const max = Math.max;
|
const max = Math.max;
|
||||||
@@ -95,7 +93,7 @@ export class GraphicsAssembler implements IAssembler {
|
|||||||
let meshBuffer = renderData;
|
let meshBuffer = renderData;
|
||||||
|
|
||||||
const maxVertexCount = meshBuffer ? meshBuffer.vertexStart + vertexCount : 0;
|
const maxVertexCount = meshBuffer ? meshBuffer.vertexStart + vertexCount : 0;
|
||||||
if (maxVertexCount > MAX_VERTEX || maxVertexCount * 3 > MAX_INDICES) {
|
if (maxVertexCount > MAX_VERTEX_COUNT) {
|
||||||
++_impl.dataOffset;
|
++_impl.dataOffset;
|
||||||
|
|
||||||
if (_impl.dataOffset < renderDataList.length) {
|
if (_impl.dataOffset < renderDataList.length) {
|
||||||
@@ -109,7 +107,7 @@ export class GraphicsAssembler implements IAssembler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (meshBuffer && meshBuffer.vertexCount < maxVertexCount) {
|
if (meshBuffer && meshBuffer.vertexCount < maxVertexCount) {
|
||||||
meshBuffer.request(vertexCount, vertexCount * 3);
|
meshBuffer.request(vertexCount, vertexCount * INDICES_PER_VERTEX);
|
||||||
}
|
}
|
||||||
|
|
||||||
return renderData;
|
return renderData;
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import { safeMeasureText, BASELINE_RATIO, MIDDLE_RATIO, getBaselineOffset, getSy
|
|||||||
import { director, DirectorEvent } from '../../../game/director';
|
import { director, DirectorEvent } from '../../../game/director';
|
||||||
import { ccwindow } from '../../../core/global-exports';
|
import { ccwindow } from '../../../core/global-exports';
|
||||||
import { TextureBase } from '../../../asset/assets/texture-base';
|
import { TextureBase } from '../../../asset/assets/texture-base';
|
||||||
|
import { buildFontDesc, CssFontFamily, DEFAULT_FONT_FAMILY } from '../../utils/font-family';
|
||||||
|
|
||||||
export interface ISharedLabelData {
|
export interface ISharedLabelData {
|
||||||
canvas: HTMLCanvasElement;
|
canvas: HTMLCanvasElement;
|
||||||
@@ -102,7 +103,7 @@ interface ILabelInfo {
|
|||||||
fontSize: number;
|
fontSize: number;
|
||||||
lineHeight: number;
|
lineHeight: number;
|
||||||
hash: string;
|
hash: string;
|
||||||
fontFamily: string;
|
fontFamily: CssFontFamily;
|
||||||
fontDesc: string;
|
fontDesc: string;
|
||||||
hAlign: number;
|
hAlign: number;
|
||||||
vAlign: number;
|
vAlign: number;
|
||||||
@@ -194,10 +195,7 @@ class LetterTexture {
|
|||||||
// Add a white background to avoid black edges.
|
// Add a white background to avoid black edges.
|
||||||
context.fillStyle = _backgroundStyle;
|
context.fillStyle = _backgroundStyle;
|
||||||
context.fillRect(0, 0, width, height);
|
context.fillRect(0, 0, width, height);
|
||||||
context.font = labelInfo.fontDesc.replace(
|
context.font = buildFontDesc(labelInfo.fontSize * fontScale, labelInfo.fontFamily);
|
||||||
/(\d+)(\.\d+)?(px|em|rem|pt)/g,
|
|
||||||
(w, m: string, n: string, u: string) => (+m * fontScale + (+n || 0) * fontScale).toString() + u,
|
|
||||||
);
|
|
||||||
|
|
||||||
const fontSize = labelInfo.fontSize * fontScale;
|
const fontSize = labelInfo.fontSize * fontScale;
|
||||||
const startX = width / 2;
|
const startX = width / 2;
|
||||||
@@ -425,7 +423,7 @@ export interface IShareLabelInfo {
|
|||||||
hAlign: number;
|
hAlign: number;
|
||||||
vAlign: number;
|
vAlign: number;
|
||||||
hash: string;
|
hash: string;
|
||||||
fontFamily: string;
|
fontFamily: CssFontFamily;
|
||||||
fontDesc: string;
|
fontDesc: string;
|
||||||
color: Color;
|
color: Color;
|
||||||
isOutlined: boolean;
|
isOutlined: boolean;
|
||||||
@@ -441,7 +439,7 @@ export const shareLabelInfo: IShareLabelInfo = {
|
|||||||
hAlign: 0,
|
hAlign: 0,
|
||||||
vAlign: 0,
|
vAlign: 0,
|
||||||
hash: '',
|
hash: '',
|
||||||
fontFamily: '',
|
fontFamily: DEFAULT_FONT_FAMILY,
|
||||||
fontDesc: 'Arial',
|
fontDesc: 'Arial',
|
||||||
color: Color.WHITE.clone(),
|
color: Color.WHITE.clone(),
|
||||||
isOutlined: false,
|
isOutlined: false,
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import type { Label } from '../../components';
|
|||||||
import { IAssembler } from '../../renderer/base';
|
import { IAssembler } from '../../renderer/base';
|
||||||
import { BmfontUtils } from './bmfontUtils';
|
import { BmfontUtils } from './bmfontUtils';
|
||||||
import { shareLabelInfo, LetterAtlas, computeHash, LetterRenderTexture } from './font-utils';
|
import { shareLabelInfo, LetterAtlas, computeHash, LetterRenderTexture } from './font-utils';
|
||||||
|
import { buildFontDesc, CssFontFamily, getCanvasFontFamily } from '../../utils/font-family';
|
||||||
|
|
||||||
const _atlasWidth = 1024;
|
const _atlasWidth = 1024;
|
||||||
const _atlasHeight = 1024;
|
const _atlasHeight = 1024;
|
||||||
@@ -59,17 +60,8 @@ export class LetterFont extends BmfontUtils {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected _getFontFamily (comp: Label): string {
|
protected _getFontFamily (comp: Label): CssFontFamily {
|
||||||
let fontFamily = 'Arial';
|
return getCanvasFontFamily(comp);
|
||||||
if (!comp.useSystemFont) {
|
|
||||||
if (comp.font) {
|
|
||||||
fontFamily = comp.font._nativeAsset || 'Arial';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
fontFamily = comp.fontFamily || 'Arial';
|
|
||||||
}
|
|
||||||
|
|
||||||
return fontFamily;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected _updateLabelInfo (comp: Label): void {
|
protected _updateLabelInfo (comp: Label): void {
|
||||||
@@ -79,12 +71,6 @@ export class LetterFont extends BmfontUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected _getFontDesc (): string {
|
protected _getFontDesc (): string {
|
||||||
let fontDesc = `${shareLabelInfo.fontSize.toString()}px `;
|
return buildFontDesc(shareLabelInfo.fontSize, shareLabelInfo.fontFamily, _isBold);
|
||||||
fontDesc += shareLabelInfo.fontFamily;
|
|
||||||
if (_isBold) {
|
|
||||||
fontDesc = `bold ${fontDesc}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return fontDesc;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ import {
|
|||||||
safeMeasureText,
|
safeMeasureText,
|
||||||
} from '../../utils/text-utils';
|
} from '../../utils/text-utils';
|
||||||
import type { Batcher2D } from '../../renderer/batcher-2d';
|
import type { Batcher2D } from '../../renderer/batcher-2d';
|
||||||
|
import { buildFontDesc, CssFontFamily } from '../../utils/font-family';
|
||||||
|
|
||||||
const Alignment = [
|
const Alignment = [
|
||||||
'left', // macro.TextAlignment.LEFT
|
'left', // macro.TextAlignment.LEFT
|
||||||
@@ -115,7 +116,7 @@ export class TextProcessing {
|
|||||||
const maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
|
const maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
|
||||||
const canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
|
const canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
|
||||||
this._fontScale *= canvasScaleToMaxSizeRatio;
|
this._fontScale *= canvasScaleToMaxSizeRatio;
|
||||||
this._fontScale = Math.max(1, this._fontScale);
|
this._fontScale = Math.max(0.1, this._fontScale);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._updatePaddingRect(style, outputLayoutData);
|
this._updatePaddingRect(style, outputLayoutData);
|
||||||
@@ -260,18 +261,8 @@ export class TextProcessing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// can cache
|
// can cache
|
||||||
private _getFontDesc (fontSize: number, fontFamily: string, isBold: boolean, isItalic: boolean): string {
|
private _getFontDesc (fontSize: number, fontFamily: CssFontFamily, isBold: boolean, isItalic: boolean): string {
|
||||||
let fontDesc = `${fontSize.toString()}px `;
|
return buildFontDesc(fontSize, fontFamily, isBold, isItalic);
|
||||||
fontDesc += fontFamily;
|
|
||||||
if (isBold) {
|
|
||||||
fontDesc = `bold ${fontDesc}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isItalic) {
|
|
||||||
fontDesc = `italic ${fontDesc}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return fontDesc;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// can cache
|
// can cache
|
||||||
|
|||||||
@@ -25,6 +25,7 @@
|
|||||||
import { Color } from '../../../core';
|
import { Color } from '../../../core';
|
||||||
import { IConfig } from '../../assets/bitmap-font';
|
import { IConfig } from '../../assets/bitmap-font';
|
||||||
import { SpriteFrame } from '../../assets/sprite-frame';
|
import { SpriteFrame } from '../../assets/sprite-frame';
|
||||||
|
import { CssFontFamily, DEFAULT_FONT_FAMILY } from '../../utils/font-family';
|
||||||
|
|
||||||
export class TextStyle {
|
export class TextStyle {
|
||||||
// ---------------ttf extra part-----------------
|
// ---------------ttf extra part-----------------
|
||||||
@@ -59,7 +60,7 @@ export class TextStyle {
|
|||||||
public bmfontScale = 1.0;// both
|
public bmfontScale = 1.0;// both
|
||||||
|
|
||||||
// font info // todo merge to font
|
// font info // todo merge to font
|
||||||
public fontFamily = 'Arial'; // both
|
public fontFamily: CssFontFamily = DEFAULT_FONT_FAMILY; // Serialized CSS family, both TTF and CHAR.
|
||||||
public fontDesc = ''; // both
|
public fontDesc = ''; // both
|
||||||
|
|
||||||
// -----------------------bitMap extra part-------------------------
|
// -----------------------bitMap extra part-------------------------
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import type { TextStyle } from './text-style';
|
|||||||
import type { TextLayout } from './text-layout';
|
import type { TextLayout } from './text-layout';
|
||||||
import { view } from '../../../ui/view';
|
import { view } from '../../../ui/view';
|
||||||
import { approx } from '../../../core';
|
import { approx } from '../../../core';
|
||||||
|
import { CssFontFamily, getCanvasFontFamily } from '../../utils/font-family';
|
||||||
|
|
||||||
const Overflow = Label.Overflow;
|
const Overflow = Label.Overflow;
|
||||||
|
|
||||||
@@ -192,18 +193,8 @@ export class TTFUtils {
|
|||||||
// no needs to update uv data
|
// no needs to update uv data
|
||||||
}
|
}
|
||||||
|
|
||||||
_updateFontFamily (comp: Label): string {
|
_updateFontFamily (comp: Label): CssFontFamily {
|
||||||
let _fontFamily = '';
|
return getCanvasFontFamily(comp);
|
||||||
if (!comp.useSystemFont) {
|
|
||||||
if (comp.font) {
|
|
||||||
_fontFamily = comp.font._nativeAsset || 'Arial';
|
|
||||||
} else {
|
|
||||||
_fontFamily = 'Arial';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
_fontFamily = comp.fontFamily || 'Arial';
|
|
||||||
}
|
|
||||||
return _fontFamily;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_calDynamicAtlas (comp: Label, outputLayoutData: TextOutputLayoutData): void {
|
_calDynamicAtlas (comp: Label, outputLayoutData: TextOutputLayoutData): void {
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import { Color, warnID, cclegacy } from '../../core';
|
|||||||
import { scene } from '../../render-scene';
|
import { scene } from '../../render-scene';
|
||||||
import type { IBatcher } from '../renderer/i-batcher';
|
import type { IBatcher } from '../renderer/i-batcher';
|
||||||
import { LineCap, LineJoin } from '../assembler/graphics/types';
|
import { LineCap, LineJoin } from '../assembler/graphics/types';
|
||||||
|
import { MAX_VERTEX_COUNT, MAX_INDEX_COUNT } from '../assembler/graphics/constants';
|
||||||
import { Impl } from '../assembler/graphics/webgl/impl';
|
import { Impl } from '../assembler/graphics/webgl/impl';
|
||||||
import { Material, RenderingSubMesh } from '../../asset/assets';
|
import { Material, RenderingSubMesh } from '../../asset/assets';
|
||||||
import { Format, PrimitiveMode, Attribute, Device, BufferUsageBit, BufferInfo, MemoryUsageBit, deviceManager } from '../../gfx';
|
import { Format, PrimitiveMode, Attribute, Device, BufferUsageBit, BufferInfo, MemoryUsageBit, deviceManager } from '../../gfx';
|
||||||
@@ -39,6 +40,8 @@ import { vfmtPosColor, getAttributeStride, getComponentPerVertex } from '../rend
|
|||||||
import { NativeUIModelProxy } from '../renderer/native-2d';
|
import { NativeUIModelProxy } from '../renderer/native-2d';
|
||||||
import { RenderEntity, RenderEntityType } from '../renderer/render-entity';
|
import { RenderEntity, RenderEntityType } from '../renderer/render-entity';
|
||||||
import type { GraphicsAssembler } from '../assembler/graphics/webgl/graphics-assembler';
|
import type { GraphicsAssembler } from '../assembler/graphics/webgl/graphics-assembler';
|
||||||
|
import type { MeshRenderData } from '../renderer/render-data';
|
||||||
|
import type { InputAssembler } from '../../gfx';
|
||||||
|
|
||||||
const attributes = vfmtPosColor.concat([
|
const attributes = vfmtPosColor.concat([
|
||||||
new Attribute('a_dist', Format.R32F),
|
new Attribute('a_dist', Format.R32F),
|
||||||
@@ -48,6 +51,15 @@ const componentPerVertex = getComponentPerVertex(attributes);
|
|||||||
|
|
||||||
const stride = getAttributeStride(attributes);
|
const stride = getAttributeStride(attributes);
|
||||||
|
|
||||||
|
// Grow only, by powers of two, so a changing geometry does not re-create the GPU buffer every frame.
|
||||||
|
function growCapacity (needed: number, current: number, max: number): number {
|
||||||
|
let cap = Math.max(current, 1);
|
||||||
|
while (cap < needed) {
|
||||||
|
cap *= 2;
|
||||||
|
}
|
||||||
|
return Math.min(cap, max);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en
|
* @en
|
||||||
* Graphics component.
|
* Graphics component.
|
||||||
@@ -266,6 +278,15 @@ export class Graphics extends UIRenderer {
|
|||||||
this._updateMtlForGraphics();
|
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 {
|
public onDestroy (): void {
|
||||||
this._sceneGetter = null;
|
this._sceneGetter = null;
|
||||||
if (JSB) {
|
if (JSB) {
|
||||||
@@ -626,7 +647,7 @@ export class Graphics extends UIRenderer {
|
|||||||
/**
|
/**
|
||||||
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
|
* @deprecated since v3.7.0, this is an engine private interface that will be removed in the future.
|
||||||
*/
|
*/
|
||||||
public activeSubModel (idx: number): void {
|
public activeSubModel (idx: number, vertexCount = 1, indexCount = 1): void {
|
||||||
if (!this.model) {
|
if (!this.model) {
|
||||||
warnID(4500, this.node.name);
|
warnID(4500, this.node.name);
|
||||||
return;
|
return;
|
||||||
@@ -637,13 +658,13 @@ export class Graphics extends UIRenderer {
|
|||||||
const vertexBuffer = gfxDevice.createBuffer(new BufferInfo(
|
const vertexBuffer = gfxDevice.createBuffer(new BufferInfo(
|
||||||
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
|
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
|
||||||
MemoryUsageBit.DEVICE,
|
MemoryUsageBit.DEVICE,
|
||||||
65535 * stride,
|
growCapacity(vertexCount, 0, MAX_VERTEX_COUNT) * stride,
|
||||||
stride,
|
stride,
|
||||||
));
|
));
|
||||||
const indexBuffer = gfxDevice.createBuffer(new BufferInfo(
|
const indexBuffer = gfxDevice.createBuffer(new BufferInfo(
|
||||||
BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST,
|
BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST,
|
||||||
MemoryUsageBit.DEVICE,
|
MemoryUsageBit.DEVICE,
|
||||||
65535 * Uint16Array.BYTES_PER_ELEMENT * 2,
|
growCapacity(indexCount, 0, MAX_INDEX_COUNT) * Uint16Array.BYTES_PER_ELEMENT,
|
||||||
Uint16Array.BYTES_PER_ELEMENT,
|
Uint16Array.BYTES_PER_ELEMENT,
|
||||||
));
|
));
|
||||||
|
|
||||||
@@ -674,6 +695,9 @@ export class Graphics extends UIRenderer {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Buffer.update() does not grow the buffer on WebGL, reserve the capacity first.
|
||||||
|
this._ensureCapacity(renderData, ia);
|
||||||
|
|
||||||
const vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex);
|
const vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex);
|
||||||
ia.vertexBuffers[0].update(vb);
|
ia.vertexBuffers[0].update(vb);
|
||||||
ia.vertexCount = renderData.vertexStart;
|
ia.vertexCount = renderData.vertexStart;
|
||||||
@@ -687,6 +711,27 @@ export class Graphics extends UIRenderer {
|
|||||||
this._isNeedUploadData = false;
|
this._isNeedUploadData = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grow only, never shrink: the capacity is reused after clear().
|
||||||
|
*/
|
||||||
|
private _ensureCapacity (renderData: MeshRenderData, ia: InputAssembler): void {
|
||||||
|
const vb = ia.vertexBuffers[0];
|
||||||
|
const vbStride = vb.stride;
|
||||||
|
if (renderData.vertexStart * vbStride > vb.size) {
|
||||||
|
const count = growCapacity(renderData.vertexStart, vb.size / vbStride, MAX_VERTEX_COUNT);
|
||||||
|
vb.resize(count * vbStride);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ib = ia.indexBuffer;
|
||||||
|
if (!ib) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (renderData.indexStart * Uint16Array.BYTES_PER_ELEMENT > ib.size) {
|
||||||
|
const count = growCapacity(renderData.indexStart, ib.size / Uint16Array.BYTES_PER_ELEMENT, MAX_INDEX_COUNT);
|
||||||
|
ib.resize(count * Uint16Array.BYTES_PER_ELEMENT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protected _render (render: IBatcher): void {
|
protected _render (render: IBatcher): void {
|
||||||
if (this._isNeedUploadData) {
|
if (this._isNeedUploadData) {
|
||||||
if (this.impl) {
|
if (this.impl) {
|
||||||
@@ -694,7 +739,8 @@ export class Graphics extends UIRenderer {
|
|||||||
const len = this.model!.subModels.length;
|
const len = this.model!.subModels.length;
|
||||||
if (renderDataList.length > len) {
|
if (renderDataList.length > len) {
|
||||||
for (let i = len; i < renderDataList.length; i++) {
|
for (let i = len; i < renderDataList.length; i++) {
|
||||||
this.activeSubModel(i);
|
const renderData = renderDataList[i];
|
||||||
|
this.activeSubModel(i, renderData.vertexStart, renderData.indexStart);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,10 +64,10 @@ function _calculateCircle (center: Vec3, radius: Vec3, segments: number): Vec3[]
|
|||||||
*/
|
*/
|
||||||
export enum MaskType {
|
export enum MaskType {
|
||||||
/**
|
/**
|
||||||
* @en Rect mask.
|
* @en Rect mask, supports rounded corners by setting radius.
|
||||||
*
|
*
|
||||||
* @zh
|
* @zh
|
||||||
* 使用矩形作为遮罩。
|
* 使用矩形作为遮罩,可通过 radius 设置圆角。
|
||||||
*/
|
*/
|
||||||
GRAPHICS_RECT = 0,
|
GRAPHICS_RECT = 0,
|
||||||
|
|
||||||
@@ -215,6 +215,32 @@ export class Mask extends Component {
|
|||||||
this._updateGraphics();
|
this._updateGraphics();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* The radius for rounded corners of rect mask.
|
||||||
|
*
|
||||||
|
* @zh
|
||||||
|
* 矩形遮罩的圆角半径。
|
||||||
|
*/
|
||||||
|
@visible(function (this: Mask) {
|
||||||
|
return this.type === MaskType.GRAPHICS_RECT;
|
||||||
|
})
|
||||||
|
@tooltip('i18n:mask.radius')
|
||||||
|
@range([0, Number.POSITIVE_INFINITY])
|
||||||
|
get radius (): number {
|
||||||
|
return this._radius;
|
||||||
|
}
|
||||||
|
|
||||||
|
set radius (value) {
|
||||||
|
const radius = clamp(value, 0, Number.POSITIVE_INFINITY);
|
||||||
|
if (this._radius === radius) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._radius = radius;
|
||||||
|
this._updateGraphics();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en
|
* @en
|
||||||
* The mask image.
|
* The mask image.
|
||||||
@@ -289,6 +315,9 @@ export class Mask extends Component {
|
|||||||
@serializable
|
@serializable
|
||||||
protected _segments = 64;
|
protected _segments = 64;
|
||||||
|
|
||||||
|
@serializable
|
||||||
|
protected _radius = 0;
|
||||||
|
|
||||||
@serializable
|
@serializable
|
||||||
protected _alphaThreshold = 0.1;
|
protected _alphaThreshold = 0.1;
|
||||||
|
|
||||||
@@ -350,7 +379,25 @@ export class Mask extends Component {
|
|||||||
testPt.y += ap.y * h;
|
testPt.y += ap.y * h;
|
||||||
|
|
||||||
let result = false;
|
let result = false;
|
||||||
if (this.type === MaskType.GRAPHICS_RECT || this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) {
|
if (this.type === MaskType.GRAPHICS_RECT) {
|
||||||
|
result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
|
||||||
|
const radius = Math.min(this._radius, w / 2, h / 2);
|
||||||
|
if (result && radius > 0) {
|
||||||
|
let dx = 0;
|
||||||
|
let dy = 0;
|
||||||
|
if (testPt.x < radius) {
|
||||||
|
dx = testPt.x - radius;
|
||||||
|
} else if (testPt.x > w - radius) {
|
||||||
|
dx = testPt.x - (w - radius);
|
||||||
|
}
|
||||||
|
if (testPt.y < radius) {
|
||||||
|
dy = testPt.y - radius;
|
||||||
|
} else if (testPt.y > h - radius) {
|
||||||
|
dy = testPt.y - (h - radius);
|
||||||
|
}
|
||||||
|
result = dx * dx + dy * dy <= radius * radius;
|
||||||
|
}
|
||||||
|
} else if (this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) {
|
||||||
result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
|
result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
|
||||||
} else if (this.type === MaskType.GRAPHICS_ELLIPSE) {
|
} else if (this.type === MaskType.GRAPHICS_ELLIPSE) {
|
||||||
const rx = w / 2;
|
const rx = w / 2;
|
||||||
@@ -423,7 +470,12 @@ export class Mask extends Component {
|
|||||||
const x = -width * ap.x;
|
const x = -width * ap.x;
|
||||||
const y = -height * ap.y;
|
const y = -height * ap.y;
|
||||||
if (this._type === MaskType.GRAPHICS_RECT) {
|
if (this._type === MaskType.GRAPHICS_RECT) {
|
||||||
graphics.rect(x, y, width, height);
|
const radius = Math.min(this._radius, width / 2, height / 2);
|
||||||
|
if (radius > 0) {
|
||||||
|
graphics.roundRect(x, y, width, height, radius);
|
||||||
|
} else {
|
||||||
|
graphics.rect(x, y, width, height);
|
||||||
|
}
|
||||||
} else if (this._type === MaskType.GRAPHICS_ELLIPSE) {
|
} else if (this._type === MaskType.GRAPHICS_ELLIPSE) {
|
||||||
const center = new Vec3(x + width / 2, y + height / 2, 0);
|
const center = new Vec3(x + width / 2, y + height / 2, 0);
|
||||||
const radius = new Vec3(width / 2, height / 2, 0);
|
const radius = new Vec3(width / 2, height / 2, 0);
|
||||||
|
|||||||
@@ -567,7 +567,7 @@ export class Sprite extends UIRenderer {
|
|||||||
if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
|
if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
|
||||||
const rtMatName = `rt-${mat.name}`;
|
const rtMatName = `rt-${mat.name}`;
|
||||||
let rtMat = builtinResMgr.get(rtMatName) as Material | null;
|
let rtMat = builtinResMgr.get(rtMatName) as Material | null;
|
||||||
if (!rtMat) {
|
if (!rtMat || !rtMat.passes.length) {
|
||||||
rtMat = new Material(rtMatName);
|
rtMat = new Material(rtMatName);
|
||||||
rtMat.copy(mat, { defines: { SAMPLE_FROM_RT: true } });
|
rtMat.copy(mat, { defines: { SAMPLE_FROM_RT: true } });
|
||||||
builtinResMgr.addAsset(rtMatName, rtMat);
|
builtinResMgr.addAsset(rtMatName, rtMat);
|
||||||
|
|||||||
@@ -398,12 +398,23 @@ export class UIRenderer extends Renderer {
|
|||||||
this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
|
this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
|
||||||
this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
|
this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
|
||||||
this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
|
this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
|
||||||
this.destroyRenderData();
|
if (!this._keepRenderData) {
|
||||||
|
this.destroyRenderData();
|
||||||
|
}
|
||||||
uiRendererManager.removeRenderer(this);
|
uiRendererManager.removeRenderer(this);
|
||||||
this._renderFlag = false;
|
this._renderFlag = false;
|
||||||
this._renderEntity.enabled = 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 {
|
public onDestroy (): void {
|
||||||
this._renderEntity.setNode(null);
|
this._renderEntity.setNode(null);
|
||||||
if (this.node._uiProps.uiComp === this) {
|
if (this.node._uiProps.uiComp === this) {
|
||||||
@@ -536,7 +547,7 @@ export class UIRenderer extends Renderer {
|
|||||||
const mat = this._updateBuiltinMaterial();
|
const mat = this._updateBuiltinMaterial();
|
||||||
this.setSharedMaterial(mat, 0);
|
this.setSharedMaterial(mat, 0);
|
||||||
if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
|
if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
|
||||||
this.getMaterialInstance(0)!.recompileShaders({ USE_ALPHA_TEST: true });
|
this.getMaterialInstance(0)?.recompileShaders({ USE_ALPHA_TEST: true });
|
||||||
}
|
}
|
||||||
this._updateBlendFunc();
|
this._updateBlendFunc();
|
||||||
}
|
}
|
||||||
@@ -600,16 +611,24 @@ export class UIRenderer extends Renderer {
|
|||||||
*/
|
*/
|
||||||
public _updateBlendFunc (): void {
|
public _updateBlendFunc (): void {
|
||||||
// todo: Not only Pass[0].target[0]
|
// todo: Not only Pass[0].target[0]
|
||||||
let target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0];
|
const renderMat = this.getRenderMaterial(0);
|
||||||
|
if (!renderMat || !renderMat.passes[0]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let target = renderMat.passes[0].blendState.targets[0];
|
||||||
this._dstBlendFactorCache = target.blendDst;
|
this._dstBlendFactorCache = target.blendDst;
|
||||||
this._srcBlendFactorCache = target.blendSrc;
|
this._srcBlendFactorCache = target.blendSrc;
|
||||||
if (this._dstBlendFactorCache !== this._dstBlendFactor || this._srcBlendFactorCache !== this._srcBlendFactor) {
|
if (this._dstBlendFactorCache !== this._dstBlendFactor || this._srcBlendFactorCache !== this._srcBlendFactor) {
|
||||||
target = this.getMaterialInstance(0)!.passes[0].blendState.targets[0];
|
const matInstance = this.getMaterialInstance(0);
|
||||||
|
if (!matInstance || !matInstance.passes[0]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
target = matInstance.passes[0].blendState.targets[0];
|
||||||
target.blend = true;
|
target.blend = true;
|
||||||
target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
|
target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
|
||||||
target.blendDst = this._dstBlendFactor;
|
target.blendDst = this._dstBlendFactor;
|
||||||
target.blendSrc = this._srcBlendFactor;
|
target.blendSrc = this._srcBlendFactor;
|
||||||
const targetPass = this.getMaterialInstance(0)!.passes[0];
|
const targetPass = matInstance.passes[0];
|
||||||
targetPass.blendState.setTarget(0, target);
|
targetPass.blendState.setTarget(0, target);
|
||||||
targetPass._updatePassHash();
|
targetPass._updatePassHash();
|
||||||
this._dstBlendFactorCache = this._dstBlendFactor;
|
this._dstBlendFactorCache = this._dstBlendFactor;
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { JSB } from 'internal:constants';
|
import { JSB } from 'internal:constants';
|
||||||
import { Device, BufferUsageBit, MemoryUsageBit, Attribute, Buffer, BufferInfo, InputAssembler, InputAssemblerInfo, Feature, API } from '../../gfx';
|
import { Device, BufferUsageBit, MemoryUsageBit, Attribute, Buffer, BufferInfo, InputAssembler, InputAssemblerInfo, Feature } from '../../gfx';
|
||||||
import { getAttributeStride } from './vertex-format';
|
import { getAttributeStride } from './vertex-format';
|
||||||
import { sys, getError, warnID, assertIsTrue } from '../../core';
|
import { sys, getError, warnID, assertIsTrue } from '../../core';
|
||||||
import { NativeUIMeshBuffer } from './native-2d';
|
import { NativeUIMeshBuffer } from './native-2d';
|
||||||
@@ -251,11 +251,10 @@ export class MeshBuffer {
|
|||||||
|
|
||||||
this.floatsPerVertex = getAttributeStride(attrs) >> 2;
|
this.floatsPerVertex = getAttributeStride(attrs) >> 2;
|
||||||
|
|
||||||
var vDataCountLimit = 65536; // 2^16 - 1
|
// Use the GPU's actual reported capability to determine max addressable vertex count.
|
||||||
const glApi = device.gfxAPI;
|
// Feature.ELEMENT_INDEX_UINT is set to true in: WebGL2, WebGPU, Vulkan, Metal, GLES3, GLES2+ext.
|
||||||
if (glApi === API.WEBGPU || glApi === API.WEBGL2 || glApi === API.WEBGL && device.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
|
// vDataCountLimit is a vertex COUNT limit (max index value + 1), not the max index value itself.
|
||||||
vDataCountLimit = 4294967295; // 2^32 - 1
|
const vDataCountLimit = device.hasFeature(Feature.ELEMENT_INDEX_UINT) ? 4294967296 : 65536; // Uint32 or Uint16 can address 2^32 or 2^16 vertices (indices 0–2^32-1 or 0–2^16-1)
|
||||||
}
|
|
||||||
assertIsTrue(this._initVDataCount / this._floatsPerVertex < vDataCountLimit, getError(9005));
|
assertIsTrue(this._initVDataCount / this._floatsPerVertex < vDataCountLimit, getError(9005));
|
||||||
|
|
||||||
if (!this.vData || !this.iData) {
|
if (!this.vData || !this.iData) {
|
||||||
@@ -396,24 +395,59 @@ export class MeshBuffer {
|
|||||||
}
|
}
|
||||||
const byteCount = this.byteOffset;
|
const byteCount = this.byteOffset;
|
||||||
const indexCount = this.indexOffset;
|
const indexCount = this.indexOffset;
|
||||||
|
const indexBytes = indexCount * 2;
|
||||||
|
let allUploaded = true;
|
||||||
for (let i = 0; i < submitCount; ++i) {
|
for (let i = 0; i < submitCount; ++i) {
|
||||||
const iaRef = this._iaPool[i];
|
const iaRef = this._iaPool[i];
|
||||||
|
|
||||||
const verticesData = new Float32Array(this.vData.buffer, 0, byteCount >> 2);
|
let verticesData = new Float32Array(this.vData.buffer, 0, byteCount >> 2);
|
||||||
const indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
|
const indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
|
||||||
|
|
||||||
|
let requiredVertexBytes = byteCount;
|
||||||
const vertexBuffer = iaRef.vertexBuffers[0];
|
const vertexBuffer = iaRef.vertexBuffers[0];
|
||||||
if (byteCount > vertexBuffer.size) {
|
if (byteCount > vertexBuffer.size) {
|
||||||
vertexBuffer.resize(byteCount);
|
vertexBuffer.resize(byteCount);
|
||||||
|
if (byteCount > vertexBuffer.size && indexCount > 0) {
|
||||||
|
let maxVertex = 0;
|
||||||
|
for (let j = 0; j < indexCount; ++j) {
|
||||||
|
if (indicesData[j] > maxVertex) {
|
||||||
|
maxVertex = indicesData[j];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const actualByteCount = (maxVertex + 1) * this._vertexFormatBytes;
|
||||||
|
if (actualByteCount < byteCount) {
|
||||||
|
requiredVertexBytes = actualByteCount;
|
||||||
|
if (actualByteCount > vertexBuffer.size) {
|
||||||
|
vertexBuffer.resize(actualByteCount);
|
||||||
|
}
|
||||||
|
verticesData = new Float32Array(this.vData.buffer, 0, actualByteCount >> 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
vertexBuffer.update(verticesData);
|
|
||||||
|
|
||||||
if (indexCount * 2 > iaRef.indexBuffer.size) {
|
const indexBuffer = iaRef.indexBuffer;
|
||||||
iaRef.indexBuffer.resize(indexCount * 2);
|
if (indexBytes > indexBuffer.size) {
|
||||||
|
indexBuffer.resize(indexBytes);
|
||||||
}
|
}
|
||||||
iaRef.indexBuffer.update(indicesData);
|
|
||||||
|
if (vertexBuffer.size < requiredVertexBytes || indexBuffer.size < indexBytes) {
|
||||||
|
allUploaded = false;
|
||||||
|
if (iOS14) {
|
||||||
|
iaRef.ia.indexCount = 0;
|
||||||
|
} else {
|
||||||
|
for (let k = 0; k < this._nextFreeIAHandle; ++k) {
|
||||||
|
this._iaPool[k].ia.indexCount = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
vertexBuffer.update(verticesData);
|
||||||
|
indexBuffer.update(indicesData);
|
||||||
|
}
|
||||||
|
if (allUploaded) {
|
||||||
|
this.dirty = false;
|
||||||
}
|
}
|
||||||
this.dirty = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private createNewIA (device: Device): IIARef {
|
private createNewIA (device: Device): IIARef {
|
||||||
|
|||||||
@@ -634,7 +634,7 @@ export class MeshRenderData extends BaseRenderData {
|
|||||||
const newVBytes = this._byteLength + vertexCount * this.stride;
|
const newVBytes = this._byteLength + vertexCount * this.stride;
|
||||||
const newICount = this.indexCount + indexCount;
|
const newICount = this.indexCount + indexCount;
|
||||||
|
|
||||||
if (vertexCount + this.vertexCount > 65535) {
|
if (vertexCount + this.vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -697,13 +697,13 @@ export class MeshRenderData extends BaseRenderData {
|
|||||||
if (this._byteLength > vertexBuffer.size) {
|
if (this._byteLength > vertexBuffer.size) {
|
||||||
vertexBuffer.resize(this._byteLength);
|
vertexBuffer.resize(this._byteLength);
|
||||||
}
|
}
|
||||||
vertexBuffer.update(verticesData);
|
vertexBuffer.update(verticesData.buffer as ArrayBuffer, this._byteLength);
|
||||||
|
|
||||||
const indexBytes = indexCount << 1;
|
const indexBytes = indexCount << 1;
|
||||||
if (indexBytes > this._indexBuffer.size) {
|
if (indexBytes > this._indexBuffer.size) {
|
||||||
this._indexBuffer.resize(indexBytes);
|
this._indexBuffer.resize(indexBytes);
|
||||||
}
|
}
|
||||||
this._indexBuffer.update(indicesData);
|
this._indexBuffer.update(indicesData.buffer as ArrayBuffer, indexBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public freeIAPool (): void {
|
public freeIAPool (): void {
|
||||||
@@ -735,6 +735,10 @@ export class MeshRenderData extends BaseRenderData {
|
|||||||
this._vertexBuffers[0].destroy();
|
this._vertexBuffers[0].destroy();
|
||||||
this._vertexBuffers = [];
|
this._vertexBuffers = [];
|
||||||
}
|
}
|
||||||
|
if (this._indexBuffer) {
|
||||||
|
this._indexBuffer.destroy();
|
||||||
|
this._indexBuffer = null!;
|
||||||
|
}
|
||||||
this._iaInfo = null!;
|
this._iaInfo = null!;
|
||||||
this.vData = new Float32Array(256 * this.stride);
|
this.vData = new Float32Array(256 * this.stride);
|
||||||
this.iData = new Uint16Array(256 * 6);
|
this.iData = new Uint16Array(256 * 6);
|
||||||
|
|||||||
@@ -165,6 +165,10 @@ export class StaticVBAccessor extends BufferAccessor {
|
|||||||
errorID(9004, byteLength);
|
errorID(9004, byteLength);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
if (vertexCount > 65536) { // Vertex count must less than 65536 for index is uint16 (0 to 65535)
|
||||||
|
errorID(9004, byteLength);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
let buf: MeshBuffer = null!;
|
let buf: MeshBuffer = null!;
|
||||||
let freeList: IFreeEntry[];
|
let freeList: IFreeEntry[];
|
||||||
let bid = 0;
|
let bid = 0;
|
||||||
@@ -176,9 +180,11 @@ export class StaticVBAccessor extends BufferAccessor {
|
|||||||
freeList = this._freeLists[i];
|
freeList = this._freeLists[i];
|
||||||
// Loop entries
|
// Loop entries
|
||||||
for (let e = 0; e < freeList.length; ++e) {
|
for (let e = 0; e < freeList.length; ++e) {
|
||||||
|
const freeEntry = freeList[e];
|
||||||
|
const vertexOffset: number = freeEntry.offset / this.vertexFormatBytes;
|
||||||
// Found suitable free entry
|
// Found suitable free entry
|
||||||
if (freeList[e].length >= byteLength) {
|
if (freeEntry.length >= byteLength && vertexOffset + (vertexCount - 1) <= 65535) {
|
||||||
entry = freeList[e];
|
entry = freeEntry;
|
||||||
bid = i;
|
bid = i;
|
||||||
eid = e;
|
eid = e;
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2026 Xiamen Yaji Software Co., Ltd.
|
||||||
|
|
||||||
|
https://www.cocos.com/
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** A CSS family expression, distinct from an asset's raw font name. */
|
||||||
|
export type CssFontFamily = string & { readonly __cssFontFamily: unique symbol };
|
||||||
|
|
||||||
|
export const DEFAULT_FONT_FAMILY = 'Arial' as CssFontFamily;
|
||||||
|
|
||||||
|
/** Serialize one raw family name as a CSS string, preserving literal quotes and commas. */
|
||||||
|
export function quoteFontFamily (name: string): CssFontFamily {
|
||||||
|
let result = '"';
|
||||||
|
for (const character of name) {
|
||||||
|
const code = character.codePointAt(0)!;
|
||||||
|
if (code === 0 || (code >= 0xD800 && code <= 0xDFFF)) {
|
||||||
|
result += '\uFFFD';
|
||||||
|
} else if (code <= 0x1F || code === 0x7F) {
|
||||||
|
result += `\\${code.toString(16)} `;
|
||||||
|
} else if (character === '"' || character === '\\') {
|
||||||
|
result += `\\${character}`;
|
||||||
|
} else {
|
||||||
|
result += character;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return `${result}"` as CssFontFamily;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FontFamilySource {
|
||||||
|
readonly useSystemFont: boolean;
|
||||||
|
readonly fontFamily: string;
|
||||||
|
readonly font: { readonly _nativeAsset: unknown } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve at the component boundary, before measurement, drawing or CSS assignment. */
|
||||||
|
export function getCanvasFontFamily (source: FontFamilySource): CssFontFamily {
|
||||||
|
const system = source.useSystemFont;
|
||||||
|
const value = system ? source.fontFamily : source.font?._nativeAsset;
|
||||||
|
const name = typeof value === 'string' && value ? value : DEFAULT_FONT_FAMILY;
|
||||||
|
return system ? name as CssFontFamily : quoteFontFamily(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Family is already serialized: changing size or style must never quote it again. */
|
||||||
|
export function buildFontDesc (size: number, family: CssFontFamily, bold = false, italic = false): string {
|
||||||
|
return `${italic ? 'italic ' : ''}${bold ? 'bold ' : ''}${size}px ${family}`;
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { warnID } from '../../core';
|
import { warnID } from '../../core';
|
||||||
import { safeMeasureText } from './text-utils';
|
import { buildFontDesc, quoteFontFamily } from './font-family';
|
||||||
import downloader from '../../asset/asset-manager/downloader';
|
import downloader from '../../asset/asset-manager/downloader';
|
||||||
import factory from '../../asset/asset-manager/factory';
|
import factory from '../../asset/asset-manager/factory';
|
||||||
import { TTFFont } from '../assets/ttf-font';
|
import { TTFFont } from '../assets/ttf-font';
|
||||||
@@ -31,10 +31,13 @@ import { ccwindow } from '../../core/global-exports';
|
|||||||
|
|
||||||
const ccdocument = ccwindow.document;
|
const ccdocument = ccwindow.document;
|
||||||
|
|
||||||
|
type FontCallback = (err: Error | null, family?: string) => void;
|
||||||
|
|
||||||
interface IFontLoadHandle {
|
interface IFontLoadHandle {
|
||||||
fontFamilyName: string;
|
fontFamilyName: string;
|
||||||
|
fontDesc: string;
|
||||||
refWidth: number;
|
refWidth: number;
|
||||||
onComplete: ((err: Error | null, data?: any | null) => void);
|
onComplete: FontCallback;
|
||||||
startTime: number;
|
startTime: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,9 +93,9 @@ function checkFontLoaded (): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const oldWidth = fontLoadHandle.refWidth;
|
const oldWidth = fontLoadHandle.refWidth;
|
||||||
const fontDesc = `40px ${fontFamily}`;
|
_canvasContext!.font = fontLoadHandle.fontDesc;
|
||||||
_canvasContext!.font = fontDesc;
|
// Font availability changes while loading; do not cache fallback-font metrics.
|
||||||
const newWidth = safeMeasureText(_canvasContext!, _testString, fontDesc);
|
const newWidth = _canvasContext!.measureText(_testString).width;
|
||||||
// loaded successfully
|
// loaded successfully
|
||||||
if (oldWidth !== newWidth) {
|
if (oldWidth !== newWidth) {
|
||||||
_loadingFonts.splice(i, 1);
|
_loadingFonts.splice(i, 1);
|
||||||
@@ -109,7 +112,7 @@ function checkFontLoaded (): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// refer to https://github.com/typekit/webfontloader/blob/master/src/core/nativefontwatchrunner.js
|
// refer to https://github.com/typekit/webfontloader/blob/master/src/core/nativefontwatchrunner.js
|
||||||
function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Error | null, data?: any | null) => void)): void {
|
function nativeCheckFontLoaded (start: number, font: string, fontDesc: string, callback: FontCallback): void {
|
||||||
const loader = new Promise<void>((resolve, reject) => {
|
const loader = new Promise<void>((resolve, reject) => {
|
||||||
const check = (): void => {
|
const check = (): void => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -117,7 +120,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Er
|
|||||||
if (now - start >= _timeout) {
|
if (now - start >= _timeout) {
|
||||||
reject();
|
reject();
|
||||||
} else {
|
} else {
|
||||||
(ccdocument as any).fonts.load(`40px ${font}`).then((fonts) => {
|
(ccdocument as any).fonts.load(fontDesc).then((fonts) => {
|
||||||
if (fonts.length >= 1) {
|
if (fonts.length >= 1) {
|
||||||
resolve();
|
resolve();
|
||||||
} else {
|
} else {
|
||||||
@@ -150,7 +153,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Er
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadFont (url: string, options: Record<string, any>, onComplete: ((err: Error | null, data?: any | null) => void)): void {
|
export function loadFont (url: string, options: Record<string, any>, onComplete: FontCallback): void {
|
||||||
const fontFamilyName = getFontFamily(url);
|
const fontFamilyName = getFontFamily(url);
|
||||||
// Already loaded fonts
|
// Already loaded fonts
|
||||||
if (_fontFaces[fontFamilyName]) {
|
if (_fontFaces[fontFamilyName]) {
|
||||||
@@ -166,17 +169,13 @@ export function loadFont (url: string, options: Record<string, any>, onComplete:
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Default width reference to test whether new font is loaded correctly
|
// Default width reference to test whether new font is loaded correctly
|
||||||
const fontDesc = `40px ${fontFamilyName}`;
|
const familyCss = quoteFontFamily(fontFamilyName);
|
||||||
|
const fontDesc = buildFontDesc(40, familyCss);
|
||||||
|
|
||||||
// Setup font face style
|
// Setup font face style
|
||||||
const fontStyle = ccdocument.createElement('style');
|
const fontStyle = ccdocument.createElement('style');
|
||||||
fontStyle.type = 'text/css';
|
fontStyle.type = 'text/css';
|
||||||
let fontStr = '';
|
let fontStr = `@font-face { font-family:${familyCss}; src:`;
|
||||||
if (Number.isNaN(fontFamilyName)) {
|
|
||||||
fontStr += `@font-face { font-family:${fontFamilyName}; src:`;
|
|
||||||
} else {
|
|
||||||
fontStr += `@font-face { font-family:"${fontFamilyName}"; src:`;
|
|
||||||
}
|
|
||||||
fontStr += `url("${url}");`;
|
fontStr += `url("${url}");`;
|
||||||
fontStyle.textContent = `${fontStr}}`;
|
fontStyle.textContent = `${fontStr}}`;
|
||||||
ccdocument.body.appendChild(fontStyle);
|
ccdocument.body.appendChild(fontStyle);
|
||||||
@@ -184,7 +183,7 @@ export function loadFont (url: string, options: Record<string, any>, onComplete:
|
|||||||
// Preload font with div
|
// Preload font with div
|
||||||
const preloadDiv = ccdocument.createElement('div');
|
const preloadDiv = ccdocument.createElement('div');
|
||||||
const divStyle = preloadDiv.style;
|
const divStyle = preloadDiv.style;
|
||||||
divStyle.fontFamily = fontFamilyName;
|
divStyle.fontFamily = familyCss;
|
||||||
preloadDiv.innerHTML = '.';
|
preloadDiv.innerHTML = '.';
|
||||||
divStyle.position = 'absolute';
|
divStyle.position = 'absolute';
|
||||||
divStyle.left = '-100px';
|
divStyle.left = '-100px';
|
||||||
@@ -192,12 +191,14 @@ export function loadFont (url: string, options: Record<string, any>, onComplete:
|
|||||||
ccdocument.body.appendChild(preloadDiv);
|
ccdocument.body.appendChild(preloadDiv);
|
||||||
|
|
||||||
if (useNativeCheck()) {
|
if (useNativeCheck()) {
|
||||||
nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete);
|
nativeCheckFontLoaded(Date.now(), fontFamilyName, fontDesc, onComplete);
|
||||||
} else {
|
} else {
|
||||||
const refWidth = safeMeasureText(_canvasContext!, _testString, fontDesc);
|
_canvasContext!.font = fontDesc;
|
||||||
|
const refWidth = _canvasContext!.measureText(_testString).width;
|
||||||
// Save loading font
|
// Save loading font
|
||||||
const fontLoadHandle = {
|
const fontLoadHandle = {
|
||||||
fontFamilyName,
|
fontFamilyName,
|
||||||
|
fontDesc,
|
||||||
refWidth,
|
refWidth,
|
||||||
onComplete,
|
onComplete,
|
||||||
startTime: Date.now(),
|
startTime: Date.now(),
|
||||||
@@ -221,9 +222,6 @@ export function getFontFamily (fontHandle: string): string {
|
|||||||
} else {
|
} else {
|
||||||
fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`;
|
fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`;
|
||||||
}
|
}
|
||||||
if (fontFamilyName.indexOf(' ') !== -1) {
|
|
||||||
fontFamilyName = `"${fontFamilyName}"`;
|
|
||||||
}
|
|
||||||
return fontFamilyName;
|
return fontFamilyName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -508,7 +508,7 @@ export class Mesh extends Asset {
|
|||||||
let dstSize = idxView.length;
|
let dstSize = idxView.length;
|
||||||
if (dstStride === 4 && !gfxDevice.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
|
if (dstStride === 4 && !gfxDevice.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
|
||||||
const vertexCount = this._struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
|
const vertexCount = this._struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
|
||||||
if (vertexCount >= 65536) {
|
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
|
||||||
warnID(10001, vertexCount, 65536);
|
warnID(10001, vertexCount, 65536);
|
||||||
continue; // Ignore this primitive
|
continue; // Ignore this primitive
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -172,13 +172,18 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
|
|||||||
// Fill index buffer.
|
// Fill index buffer.
|
||||||
let indexBuffer: ArrayBuffer | null = null;
|
let indexBuffer: ArrayBuffer | null = null;
|
||||||
let idxCount = 0;
|
let idxCount = 0;
|
||||||
const idxStride = 2;
|
let idxStride = 2;
|
||||||
|
let indexFormat = Format.R16UI;
|
||||||
if (geometry.indices) {
|
if (geometry.indices) {
|
||||||
const { indices } = geometry;
|
const { indices } = geometry;
|
||||||
idxCount = indices.length;
|
idxCount = indices.length;
|
||||||
|
if (indices.some((i) => i > 0xFFFF)) {
|
||||||
|
idxStride = 4;
|
||||||
|
indexFormat = Format.R32UI;
|
||||||
|
}
|
||||||
indexBuffer = new ArrayBuffer(idxStride * idxCount);
|
indexBuffer = new ArrayBuffer(idxStride * idxCount);
|
||||||
const indexBufferView = new DataView(indexBuffer);
|
const indexBufferView = new DataView(indexBuffer);
|
||||||
writeBuffer(indexBufferView, indices, Format.R16UI);
|
writeBuffer(indexBufferView, indices, indexFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create primitive.
|
// Create primitive.
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
import { CULL_MESHOPT, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
import { CULL_MESHOPT, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||||
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
||||||
|
|
||||||
import { sys, logID, error } from '../../core';
|
import { sys, error, debugID } from '../../core';
|
||||||
|
|
||||||
import { game } from '../../game';
|
import { game } from '../../game';
|
||||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||||
@@ -53,7 +53,7 @@ function initDecoderASM (asm_factory: any): Promise<void> {
|
|||||||
MeshoptDecoder.decodeGltfBuffer = asm_factory.decodeGltfBuffer;
|
MeshoptDecoder.decodeGltfBuffer = asm_factory.decodeGltfBuffer;
|
||||||
MeshoptDecoder.useWorkers = asm_factory.useWorkers;
|
MeshoptDecoder.useWorkers = asm_factory.useWorkers;
|
||||||
MeshoptDecoder.decodeGltfBufferAsync = asm_factory.decodeGltfBufferAsync;
|
MeshoptDecoder.decodeGltfBufferAsync = asm_factory.decodeGltfBufferAsync;
|
||||||
logID(14202);
|
debugID(14202);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ function initDecoderWASM (wasm_factory: any, wasm_url: string): Promise<void> {
|
|||||||
MeshoptDecoder.decodeGltfBuffer = wasm_factory.decodeGltfBuffer;
|
MeshoptDecoder.decodeGltfBuffer = wasm_factory.decodeGltfBuffer;
|
||||||
MeshoptDecoder.useWorkers = wasm_factory.useWorkers;
|
MeshoptDecoder.useWorkers = wasm_factory.useWorkers;
|
||||||
MeshoptDecoder.decodeGltfBufferAsync = wasm_factory.decodeGltfBufferAsync;
|
MeshoptDecoder.decodeGltfBufferAsync = wasm_factory.decodeGltfBufferAsync;
|
||||||
logID(14203);
|
debugID(14203);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -106,6 +106,13 @@ export class BakedSkinningModel extends MorphModel {
|
|||||||
UBOSkinningTexture.SIZE,
|
UBOSkinningTexture.SIZE,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The animation buffer belongs to the skinning root. Refresh its binding without
|
||||||
|
// rebuilding the instanced attribute block, which would erase custom attribute values.
|
||||||
|
for (let i = 0; i < this._subModels.length; i++) {
|
||||||
|
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
|
||||||
|
}
|
||||||
|
this.updateInstancedJointTextureInfo();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Override
|
// Override
|
||||||
|
|||||||
@@ -142,6 +142,7 @@ export class SkinningModel extends MorphModel {
|
|||||||
}
|
}
|
||||||
this._bufferIndices = null; this._joints.length = 0;
|
this._bufferIndices = null; this._joints.length = 0;
|
||||||
if (!skeleton || !skinningRoot || !mesh) { return; }
|
if (!skeleton || !skinningRoot || !mesh) { return; }
|
||||||
|
const prevRealTimeTextureMode = this._realTimeTextureMode;
|
||||||
this._realTimeTextureMode = false;
|
this._realTimeTextureMode = false;
|
||||||
if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) { this._realTimeTextureMode = true; }
|
if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) { this._realTimeTextureMode = true; }
|
||||||
this.transform = skinningRoot;
|
this.transform = skinningRoot;
|
||||||
@@ -161,6 +162,15 @@ export class SkinningModel extends MorphModel {
|
|||||||
if (!jointMaps) { indices.push(index); buffers.push(0); } else { getRelevantBuffers(indices, buffers, jointMaps, index); }
|
if (!jointMaps) { indices.push(index); buffers.push(0); } else { getRelevantBuffers(indices, buffers, jointMaps, index); }
|
||||||
this._joints.push({ indices, buffers, bound, target, bindpose, transform });
|
this._joints.push({ indices, buffers, bound, target, bindpose, transform });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rebind recreated joint resources without resetting user-provided instanced attributes.
|
||||||
|
const subModelCount = Math.min(this._subModels.length, this._bufferIndices.length);
|
||||||
|
if (subModelCount && prevRealTimeTextureMode !== this._realTimeTextureMode) {
|
||||||
|
this.onMacroPatchesStateChanged();
|
||||||
|
}
|
||||||
|
for (let i = 0; i < subModelCount; i++) {
|
||||||
|
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -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)
|
if ((this.sourceCamera.node.hasChangedFlags & TransformBit.TRS)
|
||||||
|| !this._sourceCameraPos.equals(this.sourceCamera.node.getWorldPosition())) {
|
|| !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);
|
this.probe.renderPlanarReflection(this.sourceCamera.camera);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -177,21 +177,21 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer {
|
|||||||
@override
|
@override
|
||||||
@visible(false)
|
@visible(false)
|
||||||
get mesh (): Mesh | null {
|
get mesh (): Mesh | null {
|
||||||
return super.mesh;
|
return Reflect.get(SkinnedMeshRenderer.prototype, 'mesh', this);
|
||||||
}
|
}
|
||||||
|
|
||||||
set mesh (val) {
|
set mesh (val) {
|
||||||
super.mesh = val;
|
Reflect.set(SkinnedMeshRenderer.prototype, 'mesh', val, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@visible(false)
|
@visible(false)
|
||||||
get skeleton (): Skeleton | null {
|
get skeleton (): Skeleton | null {
|
||||||
return super.skeleton;
|
return Reflect.get(SkinnedMeshRenderer.prototype, 'skeleton', this);
|
||||||
}
|
}
|
||||||
|
|
||||||
set skeleton (val) {
|
set skeleton (val) {
|
||||||
super.skeleton = val;
|
Reflect.set(SkinnedMeshRenderer.prototype, 'skeleton', val, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public onLoad (): void {
|
public onLoad (): void {
|
||||||
|
|||||||
@@ -160,7 +160,8 @@ class ClipMotionEval implements MotionEval {
|
|||||||
|
|
||||||
public overrideClips (context: AnimationGraphBindingContext): void {
|
public overrideClips (context: AnimationGraphBindingContext): void {
|
||||||
const { _originalClip: originalClip } = this;
|
const { _originalClip: originalClip } = this;
|
||||||
const overriding = context.clipOverrides?.get(originalClip);
|
const clipOverrides: any = context.clipOverrides;
|
||||||
|
const overriding: AnimationClip | null = clipOverrides && clipOverrides.get ? clipOverrides.get(originalClip) : null;
|
||||||
if (overriding) {
|
if (overriding) {
|
||||||
this._setClip(overriding, context);
|
this._setClip(overriding, context);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,6 +53,19 @@ const _windowInfo: IRenderWindowInfo = {
|
|||||||
renderPassInfo: passInfo,
|
renderPassInfo: passInfo,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// The legacy limit used only when the GPU capability is unavailable,
|
||||||
|
// e.g. in editor or during asset deserialization.
|
||||||
|
const FALLBACK_MAX_RENDER_TEXTURE_SIZE = 2048;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Gets the maximum render texture size supported by the current GPU, or null if it is unknown.
|
||||||
|
* @zh 获取当前 GPU 支持的最大渲染贴图尺寸,未知时返回 null。
|
||||||
|
*/
|
||||||
|
function getMaxRenderTextureSize (): number | null {
|
||||||
|
const maxTextureSize = deviceManager.gfxDevice?.capabilities.maxTextureSize;
|
||||||
|
return maxTextureSize && maxTextureSize > 0 ? maxTextureSize : null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en Render texture is a render target for [[Camera]] or [[Canvas]] component,
|
* @en Render texture is a render target for [[Camera]] or [[Canvas]] component,
|
||||||
* the render pipeline will use its `RenderWindow` as the target of the rendering process.
|
* the render pipeline will use its `RenderWindow` as the target of the rendering process.
|
||||||
@@ -111,12 +124,17 @@ export class RenderTexture extends TextureBase {
|
|||||||
/**
|
/**
|
||||||
* @en Resize the render texture.
|
* @en Resize the render texture.
|
||||||
* @zh 修改渲染贴图的尺寸。
|
* @zh 修改渲染贴图的尺寸。
|
||||||
* @param width @en The pixel width to resize to, the range is from 1 to 2048. @zh 需要调整到的像素宽度,范围为 1-2048。
|
* @param width @en The pixel width to resize to, the range is from 1 to the GPU max texture size.
|
||||||
* @param height @en The pixel height to resize to, the range is from 1 to 2048. @zh 需要调整到的像素高度,范围为 1-2048。
|
* @zh 需要调整到的像素宽度,范围为 1 到当前 GPU 支持的最大贴图尺寸。
|
||||||
|
* @param height @en The pixel height to resize to, the range is from 1 to the GPU max texture size.
|
||||||
|
* @zh 需要调整到的像素高度,范围为 1 到当前 GPU 支持的最大贴图尺寸。
|
||||||
|
* Note: if the GPU limit is unavailable, the legacy 2048 limit is used as a fallback.
|
||||||
|
* @zh 注意:如果无法获取 GPU 上限,则回退到旧的 2048 限制。
|
||||||
*/
|
*/
|
||||||
public resize (width: number, height: number): void {
|
public resize (width: number, height: number): void {
|
||||||
this._width = Math.floor(clamp(width, 1, 2048));
|
const maxSize = getMaxRenderTextureSize() ?? FALLBACK_MAX_RENDER_TEXTURE_SIZE;
|
||||||
this._height = Math.floor(clamp(height, 1, 2048));
|
this._width = Math.floor(clamp(width, 1, maxSize));
|
||||||
|
this._height = Math.floor(clamp(height, 1, maxSize));
|
||||||
if (this._window) {
|
if (this._window) {
|
||||||
this._window.resize(this._width, this._height);
|
this._window.resize(this._width, this._height);
|
||||||
}
|
}
|
||||||
@@ -214,7 +232,10 @@ export class RenderTexture extends TextureBase {
|
|||||||
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
|
* @deprecated Since v3.7, this is an internal engine interface and you should not call this interface under any circumstances.
|
||||||
*/
|
*/
|
||||||
public validate (): boolean {
|
public validate (): boolean {
|
||||||
return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048;
|
const maxSize = getMaxRenderTextureSize();
|
||||||
|
const validLowerBound = this.width >= 1 && this.height >= 1;
|
||||||
|
// If the GPU limit is unknown, only validate the lower bound instead of rejecting a possibly valid asset.
|
||||||
|
return validLowerBound && (maxSize === null || (this.width <= maxSize && this.height <= maxSize));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -76,10 +76,11 @@ simpleTextureProto._onGFXTextureUpdated = function (gfxTexture) {
|
|||||||
simpleTextureProto._onAfterAssignImage = function (image) {
|
simpleTextureProto._onAfterAssignImage = function (image) {
|
||||||
if (macro.CLEANUP_IMAGE_CACHE) {
|
if (macro.CLEANUP_IMAGE_CACHE) {
|
||||||
const deps = dependUtil.getDeps(this._uuid);
|
const deps = dependUtil.getDeps(this._uuid);
|
||||||
const index = deps.indexOf(image._uuid);
|
let index = deps.indexOf(image._uuid);
|
||||||
if (index !== -1) {
|
while (index !== -1) {
|
||||||
js.array.fastRemoveAt(deps, index);
|
js.array.fastRemoveAt(deps, index);
|
||||||
image.decRef();
|
image.decRef();
|
||||||
|
index = deps.indexOf(image._uuid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -194,10 +194,12 @@ export class SimpleTexture extends TextureBase {
|
|||||||
|
|
||||||
if (macro.CLEANUP_IMAGE_CACHE) {
|
if (macro.CLEANUP_IMAGE_CACHE) {
|
||||||
const deps = dependUtil.getDeps(this._uuid);
|
const deps = dependUtil.getDeps(this._uuid);
|
||||||
const index = deps.indexOf(image._uuid);
|
let index = deps.indexOf(image._uuid);
|
||||||
if (index !== -1) {
|
while (index !== -1) {
|
||||||
js.array.fastRemoveAt(deps, index);
|
js.array.fastRemoveAt(deps, index);
|
||||||
image.decRef();
|
image.decRef();
|
||||||
|
// The same UUID may occur more than once; find the next dependency edge.
|
||||||
|
index = deps.indexOf(image._uuid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,8 +195,9 @@ function define (className, baseClass, options): any {
|
|||||||
renderName = 'render_stage';
|
renderName = 'render_stage';
|
||||||
}
|
}
|
||||||
// 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里
|
// 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里
|
||||||
|
if (window.EditorExtends) {
|
||||||
window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
|
window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note: `options.ctor` should be the same as `cls` except if
|
// Note: `options.ctor` should be the same as `cls` except if
|
||||||
|
|||||||
@@ -69,6 +69,58 @@ export function approx (a: number, b: number, maxDiff?: number): boolean {
|
|||||||
return mathAbs(a - b) <= maxDiff;
|
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/>
|
* @en Clamps a value between a minimum float and maximum float value.<br/>
|
||||||
* @zh 返回最小浮点数和最大浮点数之间的一个数值。可以使用 clamp 函数将不断变化的数值限制在范围内。
|
* @zh 返回最小浮点数和最大浮点数之间的一个数值。可以使用 clamp 函数将不断变化的数值限制在范围内。
|
||||||
|
|||||||
@@ -45,5 +45,5 @@ export {
|
|||||||
DebugMode,
|
DebugMode,
|
||||||
} from './debug';
|
} from './debug';
|
||||||
|
|
||||||
export { screen } from './screen';
|
export { screen, MaxDPR } from './screen';
|
||||||
export type { Screen } from './screen';
|
export type { Screen } from './screen';
|
||||||
|
|||||||
@@ -25,12 +25,34 @@
|
|||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { screenAdapter } from 'pal/screen-adapter';
|
import { screenAdapter, IScreenOptions } from 'pal/screen-adapter';
|
||||||
import { legacyCC } from '../global-exports';
|
import { legacyCC } from '../global-exports';
|
||||||
import { Size } from '../math';
|
import { Size } from '../math';
|
||||||
import { settings, SettingsCategory } from '../settings';
|
import { settings, SettingsCategory } from '../settings';
|
||||||
import { error, warn, warnID } from './debug';
|
import { error, getError, warn, warnID } from './debug';
|
||||||
import { PalScreenEvent } from '../../../pal/screen-adapter/enum-type';
|
import type { PalScreenEvent } from '../../../pal/screen-adapter/enum-type';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Presets for the Web startup setting `screen.maxDevicePixelRatio`.
|
||||||
|
* Store the preset's numeric value or any finite number >= 1 in the startup settings.
|
||||||
|
* An omitted or null setting keeps the default cap of 2. Effective DPR never exceeds the browser DPR.
|
||||||
|
* Configure before Screen initialization; changing settings afterward does not resize the running game.
|
||||||
|
* Non-Web platforms ignore this setting. Higher caps increase pixel-related rendering costs.
|
||||||
|
* @zh Web 启动配置 `screen.maxDevicePixelRatio` 的预设档位。
|
||||||
|
* 在启动配置中保存预设的数值或任意有限且 >=1 的数字。
|
||||||
|
* 未配置或为 null 时保留默认上限 2,实际 DPR 不超过浏览器 DPR。
|
||||||
|
* 需在 Screen 初始化前配置,之后修改 settings 不会调整运行中游戏的分辨率。
|
||||||
|
* 非 Web 平台忽略该配置;提高上限会增加像素相关的渲染开销。
|
||||||
|
*/
|
||||||
|
export enum MaxDPR {
|
||||||
|
/** @en Cap DPR at 1 to reduce rendering cost. @zh 上限为 1,优先降低渲染开销。 */
|
||||||
|
Performance = 1,
|
||||||
|
/** @en Cap DPR at 2, matching the existing default. @zh 上限为 2,与现有默认策略一致。 */
|
||||||
|
Balanced = 2,
|
||||||
|
/** @en Cap DPR at 4 for higher-density rendering. @zh 上限为 4,允许更高密度渲染。 */
|
||||||
|
Quality = 4,
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en The screen API provides an easy way to do some screen managing stuff.
|
* @en The screen API provides an easy way to do some screen managing stuff.
|
||||||
* @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。
|
* @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。
|
||||||
@@ -40,10 +62,18 @@ export class Screen {
|
|||||||
* @internal
|
* @internal
|
||||||
*/
|
*/
|
||||||
public init (): void {
|
public init (): void {
|
||||||
|
// PAL decides whether to consume the setting and validates its value.
|
||||||
|
const maximum = settings.querySettings<number>(SettingsCategory.SCREEN, 'maxDevicePixelRatio');
|
||||||
const exactFitScreen = settings.querySettings(SettingsCategory.SCREEN, 'exactFitScreen') ?? true;
|
const exactFitScreen = settings.querySettings(SettingsCategory.SCREEN, 'exactFitScreen') ?? true;
|
||||||
const orientation = settings.querySettings(SettingsCategory.SCREEN, 'orientation') ?? 'auto';
|
const orientation = settings.querySettings(SettingsCategory.SCREEN, 'orientation') ?? 'auto';
|
||||||
const isHeadlessMode = settings.querySettings(SettingsCategory.RENDERING, 'renderMode') === 3;
|
const isHeadlessMode = settings.querySettings(SettingsCategory.RENDERING, 'renderMode') === 3;
|
||||||
screenAdapter.init({ exactFitScreen, configOrientation: orientation, isHeadlessMode }, (): void => {
|
const options: IScreenOptions & { maxDevicePixelRatio?: number | null } = {
|
||||||
|
exactFitScreen, configOrientation: orientation, isHeadlessMode,
|
||||||
|
};
|
||||||
|
if (maximum != null) {
|
||||||
|
options.maxDevicePixelRatio = maximum;
|
||||||
|
}
|
||||||
|
screenAdapter.init(options, (): void => {
|
||||||
const director = legacyCC.director;
|
const director = legacyCC.director;
|
||||||
if (!director.root?.pipeline) {
|
if (!director.root?.pipeline) {
|
||||||
warnID(1220);
|
warnID(1220);
|
||||||
@@ -51,6 +81,13 @@ export class Screen {
|
|||||||
}
|
}
|
||||||
director.root.pipeline.shadingScale = screenAdapter.resolutionScale;
|
director.root.pipeline.shadingScale = screenAdapter.resolutionScale;
|
||||||
});
|
});
|
||||||
|
// Only adapters exposing this capability are expected to apply the setting.
|
||||||
|
// The property check also narrows concrete adapter types in Native TS builds.
|
||||||
|
if (maximum != null
|
||||||
|
&& 'maxDevicePixelRatio' in screenAdapter
|
||||||
|
&& screenAdapter.maxDevicePixelRatio !== maximum) {
|
||||||
|
throw new Error(getError(9205));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -137,7 +174,11 @@ export class Screen {
|
|||||||
* @return {Promise|undefined}
|
* @return {Promise|undefined}
|
||||||
* @deprecated since v3.3, please use `screen.requestFullScreen(): Promise<void>` instead.
|
* @deprecated since v3.3, please use `screen.requestFullScreen(): Promise<void>` instead.
|
||||||
*/
|
*/
|
||||||
public requestFullScreen (element: HTMLElement, onFullScreenChange?: (this: Document, ev: any) => any, onFullScreenError?: (this: Document, ev: any) => any): Promise<any> | undefined;
|
public requestFullScreen (
|
||||||
|
element: HTMLElement,
|
||||||
|
onFullScreenChange?: (this: Document, ev: any) => any,
|
||||||
|
onFullScreenError?: (this: Document, ev: any) => any,
|
||||||
|
): Promise<any> | undefined;
|
||||||
/**
|
/**
|
||||||
* @en Request to enter full screen mode.
|
* @en Request to enter full screen mode.
|
||||||
* Many browsers forbid to enter full screen mode without an user intended interaction.
|
* Many browsers forbid to enter full screen mode without an user intended interaction.
|
||||||
@@ -150,7 +191,11 @@ export class Screen {
|
|||||||
* @return {Promise}
|
* @return {Promise}
|
||||||
*/
|
*/
|
||||||
public requestFullScreen (): Promise<void>;
|
public requestFullScreen (): Promise<void>;
|
||||||
public requestFullScreen (element?: HTMLElement, onFullScreenChange?: (this: Document, ev?: any) => any, onFullScreenError?: (this: Document, ev?: any) => any): Promise<any> {
|
public requestFullScreen (
|
||||||
|
element?: HTMLElement,
|
||||||
|
onFullScreenChange?: (this: Document, ev?: any) => any,
|
||||||
|
onFullScreenError?: (this: Document, ev?: any) => any,
|
||||||
|
): Promise<any> {
|
||||||
if (arguments.length > 0) {
|
if (arguments.length > 0) {
|
||||||
warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise');
|
warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,6 +88,14 @@ export abstract class CommandBuffer extends GFXObject {
|
|||||||
return this._numTris;
|
return this._numTris;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Number of compute dispatches currently recorded.
|
||||||
|
* @zh 计算调度(dispatch)次数。
|
||||||
|
*/
|
||||||
|
get numDispatches (): number {
|
||||||
|
return this._numDispatches;
|
||||||
|
}
|
||||||
|
|
||||||
/** @mangle */
|
/** @mangle */
|
||||||
protected _queue: Queue | null = null;
|
protected _queue: Queue | null = null;
|
||||||
/** @mangle */
|
/** @mangle */
|
||||||
@@ -95,6 +103,8 @@ export abstract class CommandBuffer extends GFXObject {
|
|||||||
/** @mangle */
|
/** @mangle */
|
||||||
protected _numDrawCalls = 0;
|
protected _numDrawCalls = 0;
|
||||||
/** @mangle */
|
/** @mangle */
|
||||||
|
protected _numDispatches = 0;
|
||||||
|
/** @mangle */
|
||||||
protected _numInstances = 0;
|
protected _numInstances = 0;
|
||||||
/** @mangle */
|
/** @mangle */
|
||||||
protected _numTris = 0;
|
protected _numTris = 0;
|
||||||
|
|||||||
@@ -127,6 +127,14 @@ export abstract class Device {
|
|||||||
return this._numTris;
|
return this._numTris;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Number of compute dispatches currently recorded.
|
||||||
|
* @zh 计算调度(dispatch)次数。
|
||||||
|
*/
|
||||||
|
get numDispatches (): number {
|
||||||
|
return this._numDispatches;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en Total memory size currently allocated.
|
* @en Total memory size currently allocated.
|
||||||
* @zh 内存状态。
|
* @zh 内存状态。
|
||||||
@@ -168,6 +176,8 @@ export abstract class Device {
|
|||||||
/** @mangle */
|
/** @mangle */
|
||||||
protected _numDrawCalls = 0;
|
protected _numDrawCalls = 0;
|
||||||
/** @mangle */
|
/** @mangle */
|
||||||
|
protected _numDispatches = 0;
|
||||||
|
/** @mangle */
|
||||||
protected _numInstances = 0;
|
protected _numInstances = 0;
|
||||||
/** @mangle */
|
/** @mangle */
|
||||||
protected _numTris = 0;
|
protected _numTris = 0;
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ export class EmptyBuffer extends Buffer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
public destroy (): void {}
|
public destroy (): void {}
|
||||||
public resize (size: number): void {}
|
public resize (size: number): void {
|
||||||
|
this._size = size;
|
||||||
|
this._count = this._size / this._stride;
|
||||||
|
}
|
||||||
public update (buffer: Readonly<BufferSource>, size?: number): void {}
|
public update (buffer: Readonly<BufferSource>, size?: number): void {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ import {
|
|||||||
} from './webgl-commands';
|
} from './webgl-commands';
|
||||||
import { IWebGLGPUBuffer, IWebGLGPUBufferView, WebGLIndirectDrawInfos } from './webgl-gpu-objects';
|
import { IWebGLGPUBuffer, IWebGLGPUBufferView, WebGLIndirectDrawInfos } from './webgl-gpu-objects';
|
||||||
import { WebGLDeviceManager } from './webgl-define';
|
import { WebGLDeviceManager } from './webgl-define';
|
||||||
import { warnID } from '../../core/platform/debug';
|
import { warn, warnID } from '../../core/platform/debug';
|
||||||
|
|
||||||
/** @mangle */
|
/** @mangle */
|
||||||
export class WebGLBuffer extends Buffer {
|
export class WebGLBuffer extends Buffer {
|
||||||
@@ -48,6 +48,7 @@ export class WebGLBuffer extends Buffer {
|
|||||||
private _gpuBuffer: IWebGLGPUBuffer | null = null;
|
private _gpuBuffer: IWebGLGPUBuffer | null = null;
|
||||||
private _gpuBufferView: IWebGLGPUBufferView | null = null;
|
private _gpuBufferView: IWebGLGPUBufferView | null = null;
|
||||||
private _uniformBuffer: Uint8Array | null = null;
|
private _uniformBuffer: Uint8Array | null = null;
|
||||||
|
private _lastFailedSize = 0;
|
||||||
|
|
||||||
constructor () {
|
constructor () {
|
||||||
super();
|
super();
|
||||||
@@ -125,9 +126,6 @@ export class WebGLBuffer extends Buffer {
|
|||||||
const oldSize = this._size;
|
const oldSize = this._size;
|
||||||
if (oldSize === size) { return; }
|
if (oldSize === size) { return; }
|
||||||
|
|
||||||
this._size = size;
|
|
||||||
this._count = this._size / this._stride;
|
|
||||||
|
|
||||||
if (this._uniformBuffer) {
|
if (this._uniformBuffer) {
|
||||||
this._uniformBuffer = new Uint8Array(size);
|
this._uniformBuffer = new Uint8Array(size);
|
||||||
}
|
}
|
||||||
@@ -140,8 +138,18 @@ export class WebGLBuffer extends Buffer {
|
|||||||
this._gpuBuffer.size = size;
|
this._gpuBuffer.size = size;
|
||||||
if (size > 0) {
|
if (size > 0) {
|
||||||
WebGLCmdFuncResizeBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
|
WebGLCmdFuncResizeBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
|
||||||
WebGLDeviceManager.instance.memoryStatus.bufferSize -= oldSize;
|
}
|
||||||
WebGLDeviceManager.instance.memoryStatus.bufferSize += size;
|
this._size = this._gpuBuffer.size;
|
||||||
|
this._count = this._size / this._stride;
|
||||||
|
WebGLDeviceManager.instance.memoryStatus.bufferSize -= oldSize;
|
||||||
|
WebGLDeviceManager.instance.memoryStatus.bufferSize += this._size;
|
||||||
|
if (this._size !== size) {
|
||||||
|
if (this._lastFailedSize !== size) {
|
||||||
|
this._lastFailedSize = size;
|
||||||
|
warn(`WebGLBuffer[${this.objectID}] (usage: ${this._usage}) resize failed to reach requested size: requested ${size} bytes, actual ${this._size} bytes.`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this._lastFailedSize = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -574,6 +574,8 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL
|
|||||||
} else {
|
} else {
|
||||||
gl.bufferData(WebGLConstants.ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
gl.bufferData(WebGLConstants.ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
||||||
}
|
}
|
||||||
|
gpuBuffer.size = gl.getBufferParameter(WebGLConstants.ARRAY_BUFFER, WebGLConstants.BUFFER_SIZE) as number;
|
||||||
|
|
||||||
gl.bindBuffer(WebGLConstants.ARRAY_BUFFER, null);
|
gl.bindBuffer(WebGLConstants.ARRAY_BUFFER, null);
|
||||||
stateCache.glArrayBuffer = null;
|
stateCache.glArrayBuffer = null;
|
||||||
} else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
|
} else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
|
||||||
@@ -594,6 +596,8 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL
|
|||||||
} else {
|
} else {
|
||||||
gl.bufferData(WebGLConstants.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
gl.bufferData(WebGLConstants.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
||||||
}
|
}
|
||||||
|
gpuBuffer.size = gl.getBufferParameter(WebGLConstants.ELEMENT_ARRAY_BUFFER, WebGLConstants.BUFFER_SIZE) as number;
|
||||||
|
|
||||||
gl.bindBuffer(WebGLConstants.ELEMENT_ARRAY_BUFFER, null);
|
gl.bindBuffer(WebGLConstants.ELEMENT_ARRAY_BUFFER, null);
|
||||||
stateCache.glElementArrayBuffer = null;
|
stateCache.glElementArrayBuffer = null;
|
||||||
} else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
|
} else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
|
||||||
@@ -630,6 +634,7 @@ export function WebGLCmdFuncUpdateBuffer (
|
|||||||
gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
|
gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
if (size > gpuBuffer.size) { return; }
|
||||||
const buff = buffer as ArrayBuffer;
|
const buff = buffer as ArrayBuffer;
|
||||||
const { gl, stateCache } = device;
|
const { gl, stateCache } = device;
|
||||||
|
|
||||||
@@ -2702,7 +2707,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
|
|||||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||||
@@ -2773,7 +2778,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
|
|||||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||||
stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
|
stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
|
||||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { warnID } from '../../core/platform/debug';
|
import { warn, warnID } from '../../core/platform/debug';
|
||||||
import { Buffer } from '../base/buffer';
|
import { Buffer } from '../base/buffer';
|
||||||
import { BufferUsageBit, BufferSource, BufferInfo, BufferViewInfo } from '../base/define';
|
import { BufferUsageBit, BufferSource, BufferInfo, BufferViewInfo } from '../base/define';
|
||||||
import {
|
import {
|
||||||
@@ -45,6 +45,7 @@ export class WebGL2Buffer extends Buffer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _gpuBuffer: IWebGL2GPUBuffer | null = null;
|
private _gpuBuffer: IWebGL2GPUBuffer | null = null;
|
||||||
|
private _lastFailedSize = 0;
|
||||||
|
|
||||||
public initialize (info: Readonly<BufferInfo> | Readonly<BufferViewInfo>): void {
|
public initialize (info: Readonly<BufferInfo> | Readonly<BufferViewInfo>): void {
|
||||||
if ('buffer' in info) { // buffer view
|
if ('buffer' in info) { // buffer view
|
||||||
@@ -114,15 +115,22 @@ export class WebGL2Buffer extends Buffer {
|
|||||||
const oldSize = this._size;
|
const oldSize = this._size;
|
||||||
if (oldSize === size) { return; }
|
if (oldSize === size) { return; }
|
||||||
|
|
||||||
this._size = size;
|
|
||||||
this._count = this._size / this._stride;
|
|
||||||
|
|
||||||
if (this._gpuBuffer) {
|
if (this._gpuBuffer) {
|
||||||
this._gpuBuffer.size = size;
|
this._gpuBuffer.size = size;
|
||||||
if (size > 0) {
|
if (size > 0) {
|
||||||
WebGL2CmdFuncResizeBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
|
WebGL2CmdFuncResizeBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
|
||||||
WebGL2DeviceManager.instance.memoryStatus.bufferSize -= oldSize;
|
}
|
||||||
WebGL2DeviceManager.instance.memoryStatus.bufferSize += size;
|
this._size = this._gpuBuffer.size;
|
||||||
|
this._count = this._size / this._stride;
|
||||||
|
WebGL2DeviceManager.instance.memoryStatus.bufferSize -= oldSize;
|
||||||
|
WebGL2DeviceManager.instance.memoryStatus.bufferSize += this._size;
|
||||||
|
if (this._size !== size) {
|
||||||
|
if (this._lastFailedSize !== size) {
|
||||||
|
this._lastFailedSize = size;
|
||||||
|
warn(`WebGL2Buffer[${this.objectID}] (usage: ${this._usage}) resize failed to reach requested size: requested ${size} bytes, actual ${this._size} bytes.`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this._lastFailedSize = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -770,6 +770,8 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb
|
|||||||
} else {
|
} else {
|
||||||
gl.bufferData(WebGLConstants.ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
gl.bufferData(WebGLConstants.ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
||||||
}
|
}
|
||||||
|
gpuBuffer.size = gl.getBufferParameter(WebGLConstants.ARRAY_BUFFER, WebGLConstants.BUFFER_SIZE) as number;
|
||||||
|
|
||||||
gl.bindBuffer(WebGLConstants.ARRAY_BUFFER, null);
|
gl.bindBuffer(WebGLConstants.ARRAY_BUFFER, null);
|
||||||
cache.glArrayBuffer = null;
|
cache.glArrayBuffer = null;
|
||||||
} else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
|
} else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
|
||||||
@@ -790,6 +792,8 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb
|
|||||||
} else {
|
} else {
|
||||||
gl.bufferData(WebGLConstants.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
gl.bufferData(WebGLConstants.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
|
||||||
}
|
}
|
||||||
|
gpuBuffer.size = gl.getBufferParameter(WebGLConstants.ELEMENT_ARRAY_BUFFER, WebGLConstants.BUFFER_SIZE) as number;
|
||||||
|
|
||||||
gl.bindBuffer(WebGLConstants.ELEMENT_ARRAY_BUFFER, null);
|
gl.bindBuffer(WebGLConstants.ELEMENT_ARRAY_BUFFER, null);
|
||||||
cache.glElementArrayBuffer = null;
|
cache.glElementArrayBuffer = null;
|
||||||
} else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
|
} else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
|
||||||
@@ -798,6 +802,8 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb
|
|||||||
}
|
}
|
||||||
|
|
||||||
gl.bufferData(WebGLConstants.UNIFORM_BUFFER, gpuBuffer.size, glUsage);
|
gl.bufferData(WebGLConstants.UNIFORM_BUFFER, gpuBuffer.size, glUsage);
|
||||||
|
gpuBuffer.size = gl.getBufferParameter(WebGLConstants.UNIFORM_BUFFER, WebGLConstants.BUFFER_SIZE) as number;
|
||||||
|
|
||||||
gl.bindBuffer(WebGLConstants.UNIFORM_BUFFER, null);
|
gl.bindBuffer(WebGLConstants.UNIFORM_BUFFER, null);
|
||||||
cache.glUniformBuffer = null;
|
cache.glUniformBuffer = null;
|
||||||
} else if ((gpuBuffer.usage & BufferUsageBit.INDIRECT)
|
} else if ((gpuBuffer.usage & BufferUsageBit.INDIRECT)
|
||||||
@@ -824,6 +830,7 @@ export function WebGL2CmdFuncUpdateBuffer (
|
|||||||
gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
|
gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
if (size > gpuBuffer.size) { return; }
|
||||||
const buff = buffer as ArrayBuffer;
|
const buff = buffer as ArrayBuffer;
|
||||||
const { gl } = device;
|
const { gl } = device;
|
||||||
const cache = device.getStateCache();
|
const cache = device.getStateCache();
|
||||||
@@ -2811,7 +2818,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
|||||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||||
@@ -2883,7 +2890,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
|||||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||||
extent.depth = 1;
|
extent.depth = 1;
|
||||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||||
@@ -2965,7 +2972,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
|||||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||||
offset.z = regionTexOffset.z;
|
offset.z = regionTexOffset.z;
|
||||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||||
extent.depth = regionTexExtent.depth;
|
extent.depth = regionTexExtent.depth;
|
||||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||||
@@ -2986,7 +2993,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
|||||||
|
|
||||||
if (!isCompressed) {
|
if (!isCompressed) {
|
||||||
gl.texSubImage3D(
|
gl.texSubImage3D(
|
||||||
WebGLConstants.TEXTURE_2D_ARRAY,
|
WebGLConstants.TEXTURE_3D,
|
||||||
mipLevel,
|
mipLevel,
|
||||||
offset.x,
|
offset.x,
|
||||||
offset.y,
|
offset.y,
|
||||||
@@ -3000,7 +3007,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
|||||||
);
|
);
|
||||||
} else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) {
|
} else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) {
|
||||||
gl.compressedTexSubImage3D(
|
gl.compressedTexSubImage3D(
|
||||||
WebGLConstants.TEXTURE_2D_ARRAY,
|
WebGLConstants.TEXTURE_3D,
|
||||||
mipLevel,
|
mipLevel,
|
||||||
offset.x,
|
offset.x,
|
||||||
offset.y,
|
offset.y,
|
||||||
@@ -3013,7 +3020,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
|||||||
);
|
);
|
||||||
} else { // WEBGL_compressed_texture_etc1
|
} else { // WEBGL_compressed_texture_etc1
|
||||||
gl.compressedTexImage3D(
|
gl.compressedTexImage3D(
|
||||||
WebGLConstants.TEXTURE_2D_ARRAY,
|
WebGLConstants.TEXTURE_3D,
|
||||||
mipLevel,
|
mipLevel,
|
||||||
gpuTexture.glInternalFmt,
|
gpuTexture.glInternalFmt,
|
||||||
destWidth,
|
destWidth,
|
||||||
@@ -3043,7 +3050,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
|
|||||||
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
|
||||||
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
|
||||||
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
|
||||||
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
|
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
|
||||||
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
: alignTo(regionTexExtentHeight, blockSizeHeight);
|
||||||
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
|
||||||
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
|
||||||
|
|||||||
@@ -185,7 +185,7 @@ export class WebGL2Swapchain extends Swapchain {
|
|||||||
self._canvas = info.windowHandle;
|
self._canvas = info.windowHandle;
|
||||||
|
|
||||||
self._webGL2ContextLostHandler = self._onWebGLContextLost.bind(self);
|
self._webGL2ContextLostHandler = self._onWebGLContextLost.bind(self);
|
||||||
self._canvas.addEventListener(eventWebGLContextLost, self._onWebGLContextLost);
|
self._canvas.addEventListener(eventWebGLContextLost, self._webGL2ContextLostHandler);
|
||||||
|
|
||||||
const { instance } = WebGL2DeviceManager;
|
const { instance } = WebGL2DeviceManager;
|
||||||
const { gl, capabilities } = instance;
|
const { gl, capabilities } = instance;
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ import {
|
|||||||
TextureBlit,
|
TextureBlit,
|
||||||
DescriptorSetInfo,
|
DescriptorSetInfo,
|
||||||
Format,
|
Format,
|
||||||
|
DispatchInfo,
|
||||||
} from '../base/define';
|
} from '../base/define';
|
||||||
import { Framebuffer } from '../base/framebuffer';
|
import { Framebuffer } from '../base/framebuffer';
|
||||||
import { InputAssembler } from '../base/input-assembler';
|
import { InputAssembler } from '../base/input-assembler';
|
||||||
@@ -179,6 +180,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
|||||||
private _wgpuRenderPass!: WebGPURenderPass;
|
private _wgpuRenderPass!: WebGPURenderPass;
|
||||||
|
|
||||||
private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = [];
|
private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = [];
|
||||||
|
private _computeFuncQueue: ((computePassEncoder: GPUComputePassEncoder) => void)[] = [];
|
||||||
|
|
||||||
public initialize (info: CommandBufferInfo): boolean {
|
public initialize (info: CommandBufferInfo): boolean {
|
||||||
this._type = info.type;
|
this._type = info.type;
|
||||||
@@ -222,13 +224,16 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
|||||||
this._curStencilWriteMask = null;
|
this._curStencilWriteMask = null;
|
||||||
this._curStencilCompareMask = null;
|
this._curStencilCompareMask = null;
|
||||||
this._numDrawCalls = 0;
|
this._numDrawCalls = 0;
|
||||||
|
this._numDispatches = 0;
|
||||||
this._numInstances = 0;
|
this._numInstances = 0;
|
||||||
this._numTris = 0;
|
this._numTris = 0;
|
||||||
|
this._computeFuncQueue.length = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public end (): void {
|
public end (): void {
|
||||||
this._isStateValid = false;
|
this._isStateValid = false;
|
||||||
this._isInRenderPass = false;
|
this._isInRenderPass = false;
|
||||||
|
this._computeFuncQueue.length = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public beginRenderPass (
|
public beginRenderPass (
|
||||||
@@ -650,22 +655,20 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
|||||||
this.cmdPackage.cmds.concat(cmdPackage.cmds.array);
|
this.cmdPackage.cmds.concat(cmdPackage.cmds.array);
|
||||||
|
|
||||||
this._numDrawCalls += WebGPUCmdBuff._numDrawCalls;
|
this._numDrawCalls += WebGPUCmdBuff._numDrawCalls;
|
||||||
|
this._numDispatches += WebGPUCmdBuff._numDispatches;
|
||||||
this._numInstances += WebGPUCmdBuff._numInstances;
|
this._numInstances += WebGPUCmdBuff._numInstances;
|
||||||
this._numTris += WebGPUCmdBuff._numTris;
|
this._numTris += WebGPUCmdBuff._numTris;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected bindStates (): void {
|
private _prepareDescriptorSets (): void {
|
||||||
if (!this._curGPUPipelineState) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
|
|
||||||
const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout);
|
const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout);
|
||||||
const device = WebGPUDeviceManager.instance;
|
const device = WebGPUDeviceManager.instance;
|
||||||
for (let i = 0; i < groupSets.length; i++) {
|
for (let i = 0; i < groupSets.length; i++) {
|
||||||
const currSetIdx = groupSets[i];
|
const currSetIdx = groupSets[i];
|
||||||
const currDesc = descriptorSets[currSetIdx];
|
const currDesc = descriptorSets[currSetIdx];
|
||||||
if (currDesc && currDesc.gpuDescriptorSet) {
|
if (currDesc && currDesc.gpuDescriptorSet) {
|
||||||
|
// prepare() builds the bind group if it was never created, or rebuilds it on resource change.
|
||||||
currDesc.prepare();
|
currDesc.prepare();
|
||||||
} else {
|
} else {
|
||||||
const currLayout = wgpuPipLayout.setLayouts[currSetIdx];
|
const currLayout = wgpuPipLayout.setLayouts[currSetIdx];
|
||||||
@@ -675,23 +678,13 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
|||||||
newDescSet.prepare(true);
|
newDescSet.prepare(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const gpuIA = this._curGPUInputAssembler!;
|
}
|
||||||
// only 4x MSAA is supported
|
|
||||||
gpuIA.samples = samples > 1 ? 4 : 1;
|
/**
|
||||||
this._curWebGPUPipelineState!.prepare(gpuIA);
|
* Collect the bind groups and dynamic offsets for the currently bound descriptor sets.
|
||||||
// ----------------------------wgpu pipline state-----------------------------
|
* Shared by the draw (bindStates) and compute (dispatch) paths.
|
||||||
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
|
*/
|
||||||
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
|
private _collectBindGroups (): { wgpuBindGroups: GPUBindGroup[]; wgpuDynOffsets: number[][] } {
|
||||||
passEncoder.setPipeline(wgpuPipeline);
|
|
||||||
};
|
|
||||||
this._renderPassFuncQueue.push(pplFunc);
|
|
||||||
if (this._curGPUPipelineState.pipelineState?.depthStencil) {
|
|
||||||
const stencilRef = this._curGPUPipelineState.stencilRef;
|
|
||||||
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
|
|
||||||
passEncoder.setStencilReference(stencilRef);
|
|
||||||
};
|
|
||||||
this._renderPassFuncQueue.push(stencilRefFunc);
|
|
||||||
}
|
|
||||||
const currGPUDescSize = groupSets.length;
|
const currGPUDescSize = groupSets.length;
|
||||||
const wgpuBindGroups = new Array<GPUBindGroup>(currGPUDescSize);
|
const wgpuBindGroups = new Array<GPUBindGroup>(currGPUDescSize);
|
||||||
const wgpuDynOffsets = new Array<number[]>(currGPUDescSize);
|
const wgpuDynOffsets = new Array<number[]>(currGPUDescSize);
|
||||||
@@ -703,7 +696,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
|||||||
wgpuDynOffsets[currSetIdx] = [...this._curDynamicOffsets[currSetIdx]];
|
wgpuDynOffsets[currSetIdx] = [...this._curDynamicOffsets[currSetIdx]];
|
||||||
if (!descObj.dynamicOffsetCount) {
|
if (!descObj.dynamicOffsetCount) {
|
||||||
wgpuDynOffsets[currSetIdx] = [];
|
wgpuDynOffsets[currSetIdx] = [];
|
||||||
} else if (descObj && descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
|
} else if (descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
|
||||||
wgpuDynOffsets[currSetIdx].length = descObj.dynamicOffsetCount;
|
wgpuDynOffsets[currSetIdx].length = descObj.dynamicOffsetCount;
|
||||||
for (let j = 0; j < descObj.dynamicOffsetCount; j++) {
|
for (let j = 0; j < descObj.dynamicOffsetCount; j++) {
|
||||||
const currOffset = wgpuDynOffsets[currSetIdx][j];
|
const currOffset = wgpuDynOffsets[currSetIdx][j];
|
||||||
@@ -719,16 +712,84 @@ export class WebGPUCommandBuffer extends CommandBuffer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return { wgpuBindGroups, wgpuDynOffsets };
|
||||||
|
}
|
||||||
|
|
||||||
|
public dispatch (info: DispatchInfo): void {
|
||||||
|
if (!this._curGPUPipelineState) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Prepare descriptor sets (same logic as bindStates)
|
||||||
|
this._prepareDescriptorSets();
|
||||||
|
|
||||||
|
// Create compute pipeline
|
||||||
|
this._curWebGPUPipelineState!.prepare(null!);
|
||||||
|
|
||||||
|
const computePipeline = this._curGPUPipelineState.nativePipeline as GPUComputePipeline;
|
||||||
|
|
||||||
|
// Build bind groups for compute pass
|
||||||
|
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
|
||||||
|
|
||||||
|
const func = (passEncoder: GPUComputePassEncoder): void => {
|
||||||
|
passEncoder.setPipeline(computePipeline);
|
||||||
|
const gpuBindGroupSize = wgpuBindGroups.length;
|
||||||
|
for (let i = 0; i < gpuBindGroupSize; i++) {
|
||||||
|
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
|
||||||
|
}
|
||||||
|
passEncoder.dispatchWorkgroups(info.groupCountX, info.groupCountY, info.groupCountZ);
|
||||||
|
};
|
||||||
|
this._computeFuncQueue.push(func);
|
||||||
|
++this._numDispatches;
|
||||||
|
this._isStateValid = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public submitComputePass (): void {
|
||||||
|
if (this._computeFuncQueue.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const device = WebGPUDeviceManager.instance;
|
||||||
|
const nativeDevice = device.nativeDevice!;
|
||||||
|
const cmdEncoder = nativeDevice.createCommandEncoder();
|
||||||
|
const computePassEncoder = cmdEncoder.beginComputePass();
|
||||||
|
this._computeFuncQueue.forEach((cb) => {
|
||||||
|
cb(computePassEncoder);
|
||||||
|
});
|
||||||
|
computePassEncoder.end();
|
||||||
|
nativeDevice.queue.submit([cmdEncoder.finish()]);
|
||||||
|
this._computeFuncQueue.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected bindStates (): void {
|
||||||
|
if (!this._curGPUPipelineState) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
|
||||||
|
this._prepareDescriptorSets();
|
||||||
|
const gpuIA = this._curGPUInputAssembler!;
|
||||||
|
// only 4x MSAA is supported
|
||||||
|
gpuIA.samples = samples > 1 ? 4 : 1;
|
||||||
|
this._curWebGPUPipelineState!.prepare(gpuIA);
|
||||||
|
// ----------------------------wgpu pipline state-----------------------------
|
||||||
|
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
|
||||||
|
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||||
|
passEncoder.setPipeline(wgpuPipeline);
|
||||||
|
};
|
||||||
|
this._renderPassFuncQueue.push(pplFunc);
|
||||||
|
const pipelineDesc = this._curGPUPipelineState.pipelineState;
|
||||||
|
if (pipelineDesc && 'depthStencil' in pipelineDesc && pipelineDesc.depthStencil) {
|
||||||
|
const stencilRef = this._curGPUPipelineState.stencilRef;
|
||||||
|
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||||
|
passEncoder.setStencilReference(stencilRef);
|
||||||
|
};
|
||||||
|
this._renderPassFuncQueue.push(stencilRefFunc);
|
||||||
|
}
|
||||||
|
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
|
||||||
|
|
||||||
const bgfunc = (passEncoder: GPURenderPassEncoder): void => {
|
const bgfunc = (passEncoder: GPURenderPassEncoder): void => {
|
||||||
const gpuBindGroupSize = wgpuBindGroups.length;
|
const gpuBindGroupSize = wgpuBindGroups.length;
|
||||||
for (let i = 0; i < gpuBindGroupSize; i++) {
|
for (let i = 0; i < gpuBindGroupSize; i++) {
|
||||||
let currBindGroup = wgpuBindGroups[i];
|
|
||||||
if (!currBindGroup) {
|
|
||||||
currBindGroup = (device.defaultResource.descSet as WebGPUDescriptorSet).gpuDescriptorSet.bindGroup;
|
|
||||||
}
|
|
||||||
// FIXME: this is a special sentence that 2 in 3 parameters I'm not certain.
|
// FIXME: this is a special sentence that 2 in 3 parameters I'm not certain.
|
||||||
passEncoder.setBindGroup(i, currBindGroup, wgpuDynOffsets[i]);
|
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
this._renderPassFuncQueue.push(bgfunc);
|
this._renderPassFuncQueue.push(bgfunc);
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import {
|
|||||||
TextureUsageBit,
|
TextureUsageBit,
|
||||||
ShaderStageFlags,
|
ShaderStageFlags,
|
||||||
DescriptorType,
|
DescriptorType,
|
||||||
|
MemoryAccessBit,
|
||||||
Color, Rect, Viewport, BufferTextureCopy,
|
Color, Rect, Viewport, BufferTextureCopy,
|
||||||
SamplerInfo,
|
SamplerInfo,
|
||||||
FormatSize,
|
FormatSize,
|
||||||
@@ -1423,11 +1424,15 @@ export function createBindGroupLayoutEntry (currBind: DescriptorSetLayoutBinding
|
|||||||
|
|
||||||
case DescriptorType.STORAGE_BUFFER:
|
case DescriptorType.STORAGE_BUFFER:
|
||||||
case DescriptorType.DYNAMIC_STORAGE_BUFFER:
|
case DescriptorType.DYNAMIC_STORAGE_BUFFER:
|
||||||
entry.buffer = {
|
{
|
||||||
type: 'storage',
|
const readOnly = (currBind.access & MemoryAccessBit.READ_ONLY) !== 0
|
||||||
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
|
&& (currBind.access & MemoryAccessBit.WRITE_ONLY) === 0;
|
||||||
minBindingSize: undefined,
|
entry.buffer = {
|
||||||
};
|
type: readOnly ? 'read-only-storage' : 'storage',
|
||||||
|
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
|
||||||
|
minBindingSize: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case DescriptorType.SAMPLER_TEXTURE:
|
case DescriptorType.SAMPLER_TEXTURE:
|
||||||
|
|||||||
@@ -170,9 +170,17 @@ export class WebGPUDescriptorSet extends DescriptorSet {
|
|||||||
if (descType & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) {
|
if (descType & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) {
|
||||||
this._dynamicOffsets.push(bindIdx);
|
this._dynamicOffsets.push(bindIdx);
|
||||||
}
|
}
|
||||||
} else if (descType & DESCRIPTOR_SAMPLER_TYPE) {
|
} else if (descType & (DESCRIPTOR_SAMPLER_TYPE | DescriptorType.STORAGE_IMAGE)) {
|
||||||
if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
|
const isStorageImage = (descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE;
|
||||||
// texture
|
if (isStorageImage) {
|
||||||
|
// storage texture (compute read/write): bind the texture view, no sampler
|
||||||
|
let currTex = this._textures[i] as WebGPUTexture;
|
||||||
|
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
|
||||||
|
currTex = device.defaultResource.texture;
|
||||||
|
}
|
||||||
|
this._bindTextureEntry(binding, currTex);
|
||||||
|
} else if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
|
||||||
|
// sampled texture
|
||||||
let currTex = this._textures[i] as WebGPUTexture;
|
let currTex = this._textures[i] as WebGPUTexture;
|
||||||
// null or destroyed?
|
// null or destroyed?
|
||||||
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
|
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
|
||||||
@@ -185,9 +193,9 @@ export class WebGPUDescriptorSet extends DescriptorSet {
|
|||||||
this._bindTextureEntry(binding, currTex);
|
this._bindTextureEntry(binding, currTex);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!((descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE
|
if (!isStorageImage
|
||||||
|| (descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|
&& !((descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|
||||||
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
|
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
|
||||||
// sampler
|
// sampler
|
||||||
const currSampler = (this._samplers[i] || device.defaultResource.sampler) as WebGPUSampler;
|
const currSampler = (this._samplers[i] || device.defaultResource.sampler) as WebGPUSampler;
|
||||||
this._bindSamplerEntry(binding, currSampler);
|
this._bindSamplerEntry(binding, currSampler);
|
||||||
@@ -219,7 +227,12 @@ export class WebGPUDescriptorSet extends DescriptorSet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public prepare (force: boolean = false): void {
|
public prepare (force: boolean = false): void {
|
||||||
const breakUpdate = !this._isResourceChange() && !force;
|
const gpuDescriptorSet = this._gpuDescriptorSet;
|
||||||
|
if (!gpuDescriptorSet) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Rebuild when forced, when the bind group has never been built, or when resources changed.
|
||||||
|
const breakUpdate = gpuDescriptorSet.bindGroup && !this._isResourceChange() && !force;
|
||||||
if (breakUpdate) return;
|
if (breakUpdate) return;
|
||||||
this._isDirty = true;
|
this._isDirty = true;
|
||||||
this._applyBindGroup();
|
this._applyBindGroup();
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ import { WebGPUTexture } from './webgpu-texture';
|
|||||||
import { DefaultResources, hashCombineNum, hashCombineStr, webGPU, WebGPUDeviceManager } from './define';
|
import { DefaultResources, hashCombineNum, hashCombineStr, webGPU, WebGPUDeviceManager } from './define';
|
||||||
import {
|
import {
|
||||||
Filter, Format,
|
Filter, Format,
|
||||||
QueueType, Feature, BufferTextureCopy, Rect, DescriptorSetInfo,
|
QueueType, Feature, BufferTextureCopy, Rect, Size, DescriptorSetInfo,
|
||||||
BufferInfo, BufferViewInfo, CommandBufferInfo, DeviceInfo,
|
BufferInfo, BufferViewInfo, CommandBufferInfo, DeviceInfo,
|
||||||
FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo,
|
FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo,
|
||||||
ShaderInfo, PipelineLayoutInfo, DescriptorSetLayoutInfo, TextureInfo, TextureViewInfo, GeneralBarrierInfo, TextureBarrierInfo,
|
ShaderInfo, PipelineLayoutInfo, DescriptorSetLayoutInfo, TextureInfo, TextureViewInfo, GeneralBarrierInfo, TextureBarrierInfo,
|
||||||
@@ -552,6 +552,22 @@ export class WebGPUDevice extends Device {
|
|||||||
this._caps.max3DTextureSize = limits.maxTextureDimension3D;
|
this._caps.max3DTextureSize = limits.maxTextureDimension3D;
|
||||||
this._caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment;
|
this._caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment;
|
||||||
|
|
||||||
|
// Compute limits are read from the device (not the adapter): no elevated
|
||||||
|
// compute limits are requested, so these are the values validation enforces.
|
||||||
|
const deviceLimits = device.limits;
|
||||||
|
this._caps.maxComputeSharedMemorySize = deviceLimits.maxComputeWorkgroupStorageSize;
|
||||||
|
this._caps.maxComputeWorkGroupInvocations = deviceLimits.maxComputeInvocationsPerWorkgroup;
|
||||||
|
this._caps.maxComputeWorkGroupSize = new Size(
|
||||||
|
deviceLimits.maxComputeWorkgroupSizeX,
|
||||||
|
deviceLimits.maxComputeWorkgroupSizeY,
|
||||||
|
deviceLimits.maxComputeWorkgroupSizeZ,
|
||||||
|
);
|
||||||
|
this._caps.maxComputeWorkGroupCount = new Size(
|
||||||
|
deviceLimits.maxComputeWorkgroupsPerDimension,
|
||||||
|
deviceLimits.maxComputeWorkgroupsPerDimension,
|
||||||
|
deviceLimits.maxComputeWorkgroupsPerDimension,
|
||||||
|
);
|
||||||
|
|
||||||
const features = this._adapter!.features;
|
const features = this._adapter!.features;
|
||||||
// FIXME: require by query
|
// FIXME: require by query
|
||||||
this._multiDrawIndirect = false;
|
this._multiDrawIndirect = false;
|
||||||
@@ -560,6 +576,7 @@ export class WebGPUDevice extends Device {
|
|||||||
this._features[Feature.ELEMENT_INDEX_UINT] = true;
|
this._features[Feature.ELEMENT_INDEX_UINT] = true;
|
||||||
this._features[Feature.INSTANCED_ARRAYS] = true;
|
this._features[Feature.INSTANCED_ARRAYS] = true;
|
||||||
this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
|
this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
|
||||||
|
this._features[Feature.COMPUTE_SHADER] = true;
|
||||||
this.initFormatFeatures(features);
|
this.initFormatFeatures(features);
|
||||||
|
|
||||||
this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
|
this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
|
||||||
@@ -684,6 +701,7 @@ export class WebGPUDevice extends Device {
|
|||||||
public present (): void {
|
public present (): void {
|
||||||
const queue = (this._queue as unknown as WebGPUQueue);
|
const queue = (this._queue as unknown as WebGPUQueue);
|
||||||
this._numDrawCalls = queue.numDrawCalls;
|
this._numDrawCalls = queue.numDrawCalls;
|
||||||
|
this._numDispatches = queue.numDispatches;
|
||||||
this._numInstances = queue.numInstances;
|
this._numInstances = queue.numInstances;
|
||||||
this._numTris = queue.numTris;
|
this._numTris = queue.numTris;
|
||||||
queue.clear();
|
queue.clear();
|
||||||
|
|||||||
@@ -241,8 +241,8 @@ export interface IWebGPUGPUPipelineState {
|
|||||||
bs: BlendState;
|
bs: BlendState;
|
||||||
dynamicStates: DynamicStateFlagBit[];
|
dynamicStates: DynamicStateFlagBit[];
|
||||||
gpuRenderPass: IWebGPUGPURenderPass | null;
|
gpuRenderPass: IWebGPUGPURenderPass | null;
|
||||||
pipelineState: GPURenderPipelineDescriptor | undefined;
|
pipelineState: GPURenderPipelineDescriptor | GPUComputePipelineDescriptor | undefined;
|
||||||
nativePipeline: GPUPipelineBase | undefined;
|
nativePipeline: GPURenderPipeline | GPUComputePipeline | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IWebGPUGPUDescriptor {
|
export interface IWebGPUGPUDescriptor {
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import { PipelineState, PipelineStateInfo } from '../base/pipeline-state';
|
|||||||
import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects';
|
import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects';
|
||||||
import { WebGPURenderPass } from './webgpu-render-pass';
|
import { WebGPURenderPass } from './webgpu-render-pass';
|
||||||
import { WebGPUShader } from './webgpu-shader';
|
import { WebGPUShader } from './webgpu-shader';
|
||||||
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
|
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PipelineBindPoint, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
|
||||||
import { WebGPUPipelineLayout } from './webgpu-pipeline-layout';
|
import { WebGPUPipelineLayout } from './webgpu-pipeline-layout';
|
||||||
import {
|
import {
|
||||||
GFXFormatToWGPUFormat,
|
GFXFormatToWGPUFormat,
|
||||||
@@ -81,124 +81,156 @@ export class WebGPUPipelineState extends PipelineState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// colorstates
|
|
||||||
const colorAttachments = this._renderPass.colorAttachments;
|
|
||||||
const colorDescs: GPUColorTargetState[] = [];
|
|
||||||
const colAttachmentSize = colorAttachments.length;
|
|
||||||
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
|
|
||||||
for (let i = 0; i < colAttachmentSize; i++) {
|
|
||||||
const colDesc: GPUColorTargetState = {
|
|
||||||
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
|
|
||||||
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
|
|
||||||
};
|
|
||||||
if (this._bs.targets[i].blend) {
|
|
||||||
colDesc.blend = {
|
|
||||||
color: {
|
|
||||||
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
|
|
||||||
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
|
|
||||||
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
|
|
||||||
},
|
|
||||||
alpha: {
|
|
||||||
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
|
|
||||||
operation: WebGPUBlendOps[this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
|
|
||||||
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
colorDescs.push(colDesc);
|
|
||||||
}
|
|
||||||
|
|
||||||
let vertexStage: GPUProgrammableStage;
|
|
||||||
let fragmentStage: GPUProgrammableStage;
|
|
||||||
const shaderStages = (this._shader as WebGPUShader).gpuShader.gpuStages;
|
|
||||||
const stageSize = shaderStages.length;
|
|
||||||
for (let i = 0; i < stageSize; i++) {
|
|
||||||
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
|
|
||||||
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
|
|
||||||
}
|
|
||||||
|
|
||||||
const gpuShader = info.shader as WebGPUShader;
|
const gpuShader = info.shader as WebGPUShader;
|
||||||
|
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
|
||||||
|
const shaderStages = gpuShader.gpuShader.gpuStages;
|
||||||
|
|
||||||
const shaderAttrs = gpuShader.attributes;
|
if (info.bindPoint === PipelineBindPoint.COMPUTE) {
|
||||||
const attrsSize = shaderAttrs.length;
|
// ---- Compute Pipeline ----
|
||||||
for (let i = 0; i < attrsSize; i++) {
|
let computeStage: GPUProgrammableStage | undefined;
|
||||||
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
|
const stageSize = shaderStages.length;
|
||||||
}
|
for (let i = 0; i < stageSize; i++) {
|
||||||
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
|
if (shaderStages[i].type === ShaderStageFlagBit.COMPUTE) {
|
||||||
const renderPplDesc: GPURenderPipelineDescriptor = {
|
computeStage = shaderStages[i].gpuShader!;
|
||||||
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
|
}
|
||||||
vertex: {
|
|
||||||
module: vertexStage!.module,
|
|
||||||
entryPoint: 'main',
|
|
||||||
buffers: [],
|
|
||||||
},
|
|
||||||
primitive: {
|
|
||||||
topology: WebPUPrimitives[info.primitive],
|
|
||||||
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
|
|
||||||
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
|
|
||||||
},
|
|
||||||
|
|
||||||
fragment: {
|
|
||||||
module: fragmentStage!.module,
|
|
||||||
entryPoint: 'main',
|
|
||||||
targets: colorDescs,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
|
|
||||||
|
|
||||||
// depthstencil states
|
|
||||||
let stencilRef = 0;
|
|
||||||
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
|
|
||||||
const dssDesc = {} as GPUDepthStencilState;
|
|
||||||
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
|
|
||||||
dssDesc.depthWriteEnabled = this._dss.depthWrite;
|
|
||||||
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
|
|
||||||
let stencilReadMask = 0;
|
|
||||||
let stencilWriteMask = 0;
|
|
||||||
|
|
||||||
if (this._dss.stencilTestFront) {
|
|
||||||
dssDesc.stencilFront = {
|
|
||||||
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
|
|
||||||
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
|
|
||||||
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
|
|
||||||
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
|
|
||||||
};
|
|
||||||
stencilReadMask |= this._dss.stencilReadMaskFront;
|
|
||||||
stencilWriteMask |= this._dss.stencilWriteMaskFront;
|
|
||||||
stencilRef |= this._dss.stencilRefFront;
|
|
||||||
}
|
}
|
||||||
if (this._dss.stencilTestBack) {
|
|
||||||
dssDesc.stencilBack = {
|
|
||||||
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
|
|
||||||
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
|
|
||||||
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
|
|
||||||
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
|
|
||||||
};
|
|
||||||
stencilReadMask |= this._dss.stencilReadMaskBack;
|
|
||||||
stencilWriteMask |= this._dss.stencilWriteMaskBack;
|
|
||||||
stencilRef |= this._dss.stencilRefBack;
|
|
||||||
}
|
|
||||||
dssDesc.stencilReadMask = stencilReadMask;
|
|
||||||
dssDesc.stencilWriteMask = stencilWriteMask;
|
|
||||||
dssDesc.depthBias = this._rs.depthBias;
|
|
||||||
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
|
|
||||||
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
|
|
||||||
renderPplDesc.depthStencil = dssDesc;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._gpuPipelineState = {
|
const computeDesc: GPUComputePipelineDescriptor = {
|
||||||
gpuPrimitive: WebPUPrimitives[info.primitive],
|
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
|
||||||
gpuShader: gpuShader.gpuShader,
|
compute: computeStage!,
|
||||||
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
|
};
|
||||||
rs: info.rasterizerState,
|
|
||||||
dss: info.depthStencilState,
|
this._gpuPipelineState = {
|
||||||
stencilRef,
|
gpuPrimitive: 'triangle-list' as GPUPrimitiveTopology,
|
||||||
bs: info.blendState,
|
gpuShader: gpuShader.gpuShader,
|
||||||
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
|
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
|
||||||
dynamicStates,
|
rs: info.rasterizerState,
|
||||||
pipelineState: renderPplDesc,
|
dss: info.depthStencilState,
|
||||||
nativePipeline: undefined,
|
stencilRef: 0,
|
||||||
};
|
bs: info.blendState,
|
||||||
|
gpuRenderPass: null,
|
||||||
|
dynamicStates,
|
||||||
|
pipelineState: computeDesc,
|
||||||
|
nativePipeline: undefined,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// ---- Render Pipeline ----
|
||||||
|
// colorstates
|
||||||
|
const colorAttachments = this._renderPass.colorAttachments;
|
||||||
|
const colorDescs: GPUColorTargetState[] = [];
|
||||||
|
const colAttachmentSize = colorAttachments.length;
|
||||||
|
for (let i = 0; i < colAttachmentSize; i++) {
|
||||||
|
const colDesc: GPUColorTargetState = {
|
||||||
|
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
|
||||||
|
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
|
||||||
|
};
|
||||||
|
if (this._bs.targets[i].blend) {
|
||||||
|
colDesc.blend = {
|
||||||
|
color: {
|
||||||
|
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
|
||||||
|
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
|
||||||
|
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
|
||||||
|
},
|
||||||
|
alpha: {
|
||||||
|
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
|
||||||
|
operation: WebGPUBlendOps[
|
||||||
|
this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
|
||||||
|
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
colorDescs.push(colDesc);
|
||||||
|
}
|
||||||
|
|
||||||
|
let vertexStage: GPUProgrammableStage;
|
||||||
|
let fragmentStage: GPUProgrammableStage;
|
||||||
|
const stageSize = shaderStages.length;
|
||||||
|
for (let i = 0; i < stageSize; i++) {
|
||||||
|
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
|
||||||
|
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
|
||||||
|
}
|
||||||
|
|
||||||
|
const shaderAttrs = gpuShader.attributes;
|
||||||
|
const attrsSize = shaderAttrs.length;
|
||||||
|
for (let i = 0; i < attrsSize; i++) {
|
||||||
|
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
|
||||||
|
}
|
||||||
|
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
|
||||||
|
const renderPplDesc: GPURenderPipelineDescriptor = {
|
||||||
|
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
|
||||||
|
vertex: {
|
||||||
|
module: vertexStage!.module,
|
||||||
|
entryPoint: 'main',
|
||||||
|
buffers: [],
|
||||||
|
},
|
||||||
|
primitive: {
|
||||||
|
topology: WebPUPrimitives[info.primitive],
|
||||||
|
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
|
||||||
|
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
|
||||||
|
},
|
||||||
|
|
||||||
|
fragment: {
|
||||||
|
module: fragmentStage!.module,
|
||||||
|
entryPoint: 'main',
|
||||||
|
targets: colorDescs,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
|
||||||
|
|
||||||
|
// depthstencil states
|
||||||
|
let stencilRef = 0;
|
||||||
|
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
|
||||||
|
const dssDesc = {} as GPUDepthStencilState;
|
||||||
|
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
|
||||||
|
dssDesc.depthWriteEnabled = this._dss.depthWrite;
|
||||||
|
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
|
||||||
|
let stencilReadMask = 0;
|
||||||
|
let stencilWriteMask = 0;
|
||||||
|
|
||||||
|
if (this._dss.stencilTestFront) {
|
||||||
|
dssDesc.stencilFront = {
|
||||||
|
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
|
||||||
|
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
|
||||||
|
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
|
||||||
|
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
|
||||||
|
};
|
||||||
|
stencilReadMask |= this._dss.stencilReadMaskFront;
|
||||||
|
stencilWriteMask |= this._dss.stencilWriteMaskFront;
|
||||||
|
stencilRef |= this._dss.stencilRefFront;
|
||||||
|
}
|
||||||
|
if (this._dss.stencilTestBack) {
|
||||||
|
dssDesc.stencilBack = {
|
||||||
|
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
|
||||||
|
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
|
||||||
|
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
|
||||||
|
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
|
||||||
|
};
|
||||||
|
stencilReadMask |= this._dss.stencilReadMaskBack;
|
||||||
|
stencilWriteMask |= this._dss.stencilWriteMaskBack;
|
||||||
|
stencilRef |= this._dss.stencilRefBack;
|
||||||
|
}
|
||||||
|
dssDesc.stencilReadMask = stencilReadMask;
|
||||||
|
dssDesc.stencilWriteMask = stencilWriteMask;
|
||||||
|
dssDesc.depthBias = this._rs.depthBias;
|
||||||
|
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
|
||||||
|
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
|
||||||
|
renderPplDesc.depthStencil = dssDesc;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._gpuPipelineState = {
|
||||||
|
gpuPrimitive: WebPUPrimitives[info.primitive],
|
||||||
|
gpuShader: gpuShader.gpuShader,
|
||||||
|
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
|
||||||
|
rs: info.rasterizerState,
|
||||||
|
dss: info.depthStencilState,
|
||||||
|
stencilRef,
|
||||||
|
bs: info.blendState,
|
||||||
|
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
|
||||||
|
dynamicStates,
|
||||||
|
pipelineState: renderPplDesc,
|
||||||
|
nativePipeline: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected _getShaderLocation (name: string): number | undefined {
|
protected _getShaderLocation (name: string): number | undefined {
|
||||||
@@ -215,9 +247,22 @@ export class WebGPUPipelineState extends PipelineState {
|
|||||||
if (this._gpuPipelineState!.nativePipeline && !forceUpdate) {
|
if (this._gpuPipelineState!.nativePipeline && !forceUpdate) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const webgpuDevice = (WebGPUDeviceManager.instance);
|
||||||
|
const nativeDevice = webgpuDevice.nativeDevice;
|
||||||
|
|
||||||
|
const pipelineState = this._gpuPipelineState!.pipelineState!;
|
||||||
|
// Compute pipeline: no vertex attributes, no multisample
|
||||||
|
if ('compute' in pipelineState) {
|
||||||
|
const nativePipeline = nativeDevice?.createComputePipeline(
|
||||||
|
pipelineState,
|
||||||
|
);
|
||||||
|
this._gpuPipelineState!.nativePipeline = nativePipeline;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render pipeline
|
||||||
const gpuShader = this.shader;
|
const gpuShader = this.shader;
|
||||||
const shaderAttrs = gpuShader.attributes;
|
const shaderAttrs = gpuShader.attributes;
|
||||||
const pipelineState = this._gpuPipelineState!.pipelineState!;
|
|
||||||
const vertexAttrs: GPUVertexBufferLayout[] = [];
|
const vertexAttrs: GPUVertexBufferLayout[] = [];
|
||||||
const emptyPushAttr: string[] = [];
|
const emptyPushAttr: string[] = [];
|
||||||
const streamCount = ia.gpuVertexBuffers.length;
|
const streamCount = ia.gpuVertexBuffers.length;
|
||||||
@@ -272,8 +317,6 @@ export class WebGPUPipelineState extends PipelineState {
|
|||||||
|
|
||||||
pipelineState.vertex.buffers = vertexAttrs;
|
pipelineState.vertex.buffers = vertexAttrs;
|
||||||
pipelineState.multisample = { count: ia.samples };
|
pipelineState.multisample = { count: ia.samples };
|
||||||
const webgpuDevice = (WebGPUDeviceManager.instance);
|
|
||||||
const nativeDevice = webgpuDevice.nativeDevice;
|
|
||||||
const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState);
|
const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState);
|
||||||
this._gpuPipelineState!.nativePipeline = nativePipeline;
|
this._gpuPipelineState!.nativePipeline = nativePipeline;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { QueueInfo } from '../base/define';
|
|||||||
|
|
||||||
export class WebGPUQueue extends Queue {
|
export class WebGPUQueue extends Queue {
|
||||||
public numDrawCalls = 0;
|
public numDrawCalls = 0;
|
||||||
|
public numDispatches = 0;
|
||||||
public numInstances = 0;
|
public numInstances = 0;
|
||||||
public numTris = 0;
|
public numTris = 0;
|
||||||
|
|
||||||
@@ -51,6 +52,7 @@ export class WebGPUQueue extends Queue {
|
|||||||
for (let i = 0; i < cmdBuffSize; i++) {
|
for (let i = 0; i < cmdBuffSize; i++) {
|
||||||
const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer;
|
const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer;
|
||||||
this.numDrawCalls += cmdBuff.numDrawCalls;
|
this.numDrawCalls += cmdBuff.numDrawCalls;
|
||||||
|
this.numDispatches += cmdBuff.numDispatches;
|
||||||
this.numInstances += cmdBuff.numInstances;
|
this.numInstances += cmdBuff.numInstances;
|
||||||
this.numTris += cmdBuff.numTris;
|
this.numTris += cmdBuff.numTris;
|
||||||
}
|
}
|
||||||
@@ -59,6 +61,7 @@ export class WebGPUQueue extends Queue {
|
|||||||
|
|
||||||
public clear (): void {
|
public clear (): void {
|
||||||
this.numDrawCalls = 0;
|
this.numDrawCalls = 0;
|
||||||
|
this.numDispatches = 0;
|
||||||
this.numInstances = 0;
|
this.numInstances = 0;
|
||||||
this.numTris = 0;
|
this.numTris = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-4
@@ -380,9 +380,15 @@ export class Input {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) {
|
if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) {
|
||||||
|
// WeChat PC maps the left mouse button and configured keyboard/mouse controls to touch events.
|
||||||
|
// Use those platform touch events to avoid duplicates, while continuing to dispatch mouse events.
|
||||||
|
// https://developers.weixin.qq.com/minigame/dev/guide/open-ability/pc-game.html
|
||||||
|
const shouldSimulateTouch = !sys.hasFeature(sys.Feature.INPUT_TOUCH);
|
||||||
mouseInput.on(InputEventType.MOUSE_DOWN, (event): void => {
|
mouseInput.on(InputEventType.MOUSE_DOWN, (event): void => {
|
||||||
self._needSimulateTouchMoveEvent = true;
|
if (shouldSimulateTouch) {
|
||||||
self._simulateEventTouch(event);
|
self._needSimulateTouchMoveEvent = true;
|
||||||
|
self._simulateEventTouch(event);
|
||||||
|
}
|
||||||
self._dispatchEventMouse(event);
|
self._dispatchEventMouse(event);
|
||||||
});
|
});
|
||||||
mouseInput.on(InputEventType.MOUSE_MOVE, (event): void => {
|
mouseInput.on(InputEventType.MOUSE_MOVE, (event): void => {
|
||||||
@@ -392,8 +398,10 @@ export class Input {
|
|||||||
self._dispatchEventMouse(event);
|
self._dispatchEventMouse(event);
|
||||||
});
|
});
|
||||||
mouseInput.on(InputEventType.MOUSE_UP, (event): void => {
|
mouseInput.on(InputEventType.MOUSE_UP, (event): void => {
|
||||||
self._needSimulateTouchMoveEvent = false;
|
if (shouldSimulateTouch) {
|
||||||
self._simulateEventTouch(event);
|
self._needSimulateTouchMoveEvent = false;
|
||||||
|
self._simulateEventTouch(event);
|
||||||
|
}
|
||||||
self._dispatchEventMouse(event);
|
self._dispatchEventMouse(event);
|
||||||
});
|
});
|
||||||
mouseInput.on(InputEventType.MOUSE_WHEEL, (event): void => {
|
mouseInput.on(InputEventType.MOUSE_WHEEL, (event): void => {
|
||||||
|
|||||||
@@ -24,6 +24,12 @@
|
|||||||
|
|
||||||
import './intersect';
|
import './intersect';
|
||||||
|
|
||||||
|
// NOTE: the worker subsystem (`./worker`, `./worker-pool`) is deliberately
|
||||||
|
// NOT re-exported here. `cocos/misc` is part of the always-on `base` feature, so anything exported
|
||||||
|
// from this file ships in every build's main bundle. The worker subsystem is exposed through the
|
||||||
|
// optional `worker` and `worker-pool` features instead (see their entries in `exports/` and
|
||||||
|
// cc.config.json). Projects enabling only `worker` do not include the pool scheduler.
|
||||||
|
|
||||||
export { Camera } from './camera-component';
|
export { Camera } from './camera-component';
|
||||||
export { ModelRenderer } from './model-renderer';
|
export { ModelRenderer } from './model-renderer';
|
||||||
export { Renderer } from './renderer';
|
export { Renderer } from './renderer';
|
||||||
|
|||||||
@@ -0,0 +1,982 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2018-2023 Xiamen Yaji Software Co., Ltd.
|
||||||
|
|
||||||
|
http://www.cocos.com
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||||
|
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { IPlatformWorkerBackend } from 'pal/worker';
|
||||||
|
import {
|
||||||
|
WorkerTask, IWorker, getOptimalWorkerCount,
|
||||||
|
getWorkerBackend, resetWorkerBackendCache,
|
||||||
|
} from './worker';
|
||||||
|
import { getError, warnID } from '../core/platform/debug';
|
||||||
|
|
||||||
|
/** Execution state, independent of the host platform. */
|
||||||
|
export type WorkerExecutionMode = 'worker' | 'sync' | 'none';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Infrastructure failures (a worker that never replies / times out, errors out, fails to spawn, or
|
||||||
|
* speaks a malformed protocol) tolerated before a script-mode pool gives up on the real worker and
|
||||||
|
* degrades to single-threaded execution via `options.fallback`. Kept at 1: each of these signals
|
||||||
|
* means the worker backend is not functioning for this script, so retrying on a real worker would
|
||||||
|
* only fail again — and on the seven single-worker mini-game platforms a retry would also re-occupy
|
||||||
|
* the one worker slot. A task-level computation error (the worker replies `{ ok: false }`) is NOT an
|
||||||
|
* infrastructure failure and never counts toward this.
|
||||||
|
* @zh
|
||||||
|
* 脚本模式的池在放弃真 Worker、降级为 `options.fallback` 单线程执行之前,所能容忍的**基础设施失败**
|
||||||
|
* 次数(Worker 永不回复 / 超时、报错、创建失败、或回发非法协议)。取 1:上述任一信号都意味着该脚本的
|
||||||
|
* Worker 后端不可用,再用真 Worker 重试只会再次失败——而且在 7 个单 Worker 小游戏平台上重试还会重新
|
||||||
|
* 占掉那唯一的槽位。任务级计算错误(Worker 回发 `{ ok: false }`)**不算**基础设施失败,不计入此数。
|
||||||
|
*/
|
||||||
|
const DEGRADE_AFTER_FAILURES = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Options for [[WorkerPool]].
|
||||||
|
* @zh [[WorkerPool]] 的选项。
|
||||||
|
*/
|
||||||
|
export interface WorkerPoolOptions {
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Maximum number of concurrent workers. Extra tasks are queued and dispatched when a worker frees up.
|
||||||
|
* Default is `1`.
|
||||||
|
* @zh
|
||||||
|
* 并发 Worker 的最大数量。多余的任务会排队,等某个 Worker 空闲后再派发。默认 `1`。
|
||||||
|
*/
|
||||||
|
maxWorkers?: number;
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Idle release time in milliseconds. An idle worker is terminated after being idle for this long,
|
||||||
|
* to avoid keeping threads (and their memory) alive forever. Set to `0` to never release idle workers.
|
||||||
|
* Default is `1000` (1 second).
|
||||||
|
* @zh
|
||||||
|
* 空闲释放时间(毫秒)。Worker 空闲超过该时长后会被终止,避免线程(及其内存)长期驻留。
|
||||||
|
* 设为 `0` 表示永不释放空闲 Worker。默认 `1000`(1 秒)。
|
||||||
|
*/
|
||||||
|
idleReleaseAfter?: number;
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Synchronous fallback task (**script mode only**). It must compute the same result as the worker
|
||||||
|
* script's `runTask(args)` from the same `args`. When NO worker backend is available at all —
|
||||||
|
* the platform worker environment is not fully set up ([[checkWorkerScript]] not ready), or the
|
||||||
|
* platform has no worker API (Taobao mini-game, native) and there is no global `Worker` either —
|
||||||
|
* tasks run single-threaded on the main thread with this function instead of rejecting. If omitted
|
||||||
|
* in that situation, `run()` rejects with a descriptive error.
|
||||||
|
* Runtime failures retry non-transferred arguments only. Transferred tasks reject because
|
||||||
|
* ownership has moved; subsequent tasks use this fallback. Fallback computation must be retry-safe.
|
||||||
|
* @zh
|
||||||
|
* 同步降级任务函数(**仅脚本模式**)。它必须与 worker 脚本里的 `runTask(args)` 用相同的 `args`
|
||||||
|
* 算出相同的结果。当所有 Worker 后端都不可用时——平台 Worker 环境未设置完整
|
||||||
|
* ([[checkWorkerScript]] 不 ready),或平台根本没有 Worker API(淘宝小游戏、原生)且也没有全局
|
||||||
|
* `Worker`——任务将用它在主线程**单线程**执行,而不是直接 reject。若此时未提供该函数,
|
||||||
|
* `run()` 会以带说明的错误 reject。
|
||||||
|
* 运行时失败仅重试未移交所有权的参数;已 transfer 的任务拒绝,后续任务仍使用 fallback。
|
||||||
|
* fallback 应为可安全重试的计算逻辑。
|
||||||
|
*/
|
||||||
|
fallback?: WorkerTask;
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Per-task timeout in milliseconds. When exceeded, the task rejects with a timeout error and the
|
||||||
|
* worker running it is terminated so the pool spawns a fresh one.
|
||||||
|
*
|
||||||
|
* Default is `0` (no timeout). A timeout is the ONLY safety net against a worker that never
|
||||||
|
* replies — a worker script that fails to post back, or a worker silently reclaimed by the
|
||||||
|
* platform. Some platforms make this materially more likely: not every mini-game platform exposes
|
||||||
|
* `onError` (Huawei quick game documents only create/postMessage/onMessage/terminate), so an
|
||||||
|
* internal failure there produces no error event at all.
|
||||||
|
*
|
||||||
|
* Recommended for script mode in production: pick a bound well above your worst-case task duration.
|
||||||
|
* @zh
|
||||||
|
* 单个任务的超时时间(毫秒)。超时后任务以超时错误 reject,运行它的 Worker 会被终止,
|
||||||
|
* 池随后重建一个。
|
||||||
|
*
|
||||||
|
* 默认 `0`(不超时)。超时是对"Worker 永不回复"的**唯一**兜底——比如 Worker 脚本忘记回发结果,
|
||||||
|
* 或 Worker 被平台静默回收。部分平台让这种情况更容易发生:并非每个小游戏平台都暴露 `onError`
|
||||||
|
* (华为快游戏只文档化了 create/postMessage/onMessage/terminate),那里的内部失败根本不会产生错误事件。
|
||||||
|
*
|
||||||
|
* 生产环境的脚本模式建议设置超时:取一个明显高于最坏情况任务耗时的上界。
|
||||||
|
*/
|
||||||
|
timeout?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* A pool of workers bound to a single self-contained task function (function mode) or to a
|
||||||
|
* pre-packaged worker script (script mode — the only way to get a real worker on any mini-game
|
||||||
|
* platform, because they forbid rebuilding a function from source).
|
||||||
|
*
|
||||||
|
* It is designed for *high-frequency* workloads (e.g. per-frame physics / crowd simulation / data processing):
|
||||||
|
* instead of spawning and tearing down a worker for every call — which costs a Blob URL round-trip and
|
||||||
|
* thread startup — the pool keeps a bounded set of workers alive and reuses them, releasing idle workers
|
||||||
|
* after [[WorkerPoolOptions.idleReleaseAfter]].
|
||||||
|
*
|
||||||
|
* IMPORTANT — a pool is not always a source of parallelism. On seven of the nine mini-game platforms
|
||||||
|
* (ByteDance, Alipay, Baidu, Huawei, OPPO, vivo, Xiaomi) and on WeChat V1, the platform allows exactly
|
||||||
|
* ONE worker, so the pool is capped to one worker no matter what `maxWorkers` says. There it is an
|
||||||
|
* **asynchronous offload queue**: it keeps a long task off the main thread, but it cannot run two tasks
|
||||||
|
* at once. Gate features that need true parallelism on
|
||||||
|
* [[getWorkerCapabilities]]`()`.parallel, not on whether a worker exists.
|
||||||
|
*
|
||||||
|
* In function mode, on platforms that cannot build a worker from a serialized string (every mini-game
|
||||||
|
* platform, and native) each task simply runs synchronously on the main thread, so the pool is a
|
||||||
|
* transparent no-op wrapper. To get a real worker on a mini-game platform, use script mode:
|
||||||
|
* `new WorkerPool('workers/my-task/index.js')` — the pool then creates its worker from a pre-packaged
|
||||||
|
* script via `minigame.createWorker` (see the constructor and the bundled template).
|
||||||
|
*
|
||||||
|
* For *CPU-bound* workloads on a genuinely parallel platform, pass [[getOptimalWorkerCount]] as
|
||||||
|
* `maxWorkers` to parallelize across the available cores (leaving one core for the main thread). Note
|
||||||
|
* that `maxWorkers` only matters when you submit several independent tasks concurrently — a single
|
||||||
|
* queued task always uses exactly one worker.
|
||||||
|
*
|
||||||
|
* @zh
|
||||||
|
* 绑定到单个自包含任务函数(函数模式)或预打包 Worker 脚本(脚本模式——这是在任何小游戏平台上获得
|
||||||
|
* 真 Worker 的**唯一**方式,因为它们禁止用源码重建函数)的 Worker 池。
|
||||||
|
*
|
||||||
|
* 它面向*高频*负载(如逐帧的物理模拟、人群模拟、数据处理):与其每次调用都创建再销毁一个 Worker——
|
||||||
|
* 那会付出 Blob URL 往返和线程启动的成本——池会保活一个有上限的 Worker 集合并复用,
|
||||||
|
* 空闲超过 [[WorkerPoolOptions.idleReleaseAfter]] 的 Worker 会被释放。
|
||||||
|
*
|
||||||
|
* **重要——池并不总是并行来源。** 9 个小游戏平台中有 7 个(抖音、支付宝、百度、华为、OPPO、vivo、小米)
|
||||||
|
* 以及微信 V1,平台只允许**恰好 1 个** Worker,因此无论 `maxWorkers` 传什么,池都会被封顶到 1 个。
|
||||||
|
* 在这些平台上它是一个**异步卸载队列**:能把长任务从主线程挪走,但无法同时跑两个任务。
|
||||||
|
* 需要真并行的特性,请以 [[getWorkerCapabilities]]`()`.parallel 为准,而不是以"有没有 Worker"为准。
|
||||||
|
*
|
||||||
|
* 在函数模式下,凡是无法从序列化字符串构建 Worker 的平台(全部小游戏平台、原生),每个任务直接在主线程
|
||||||
|
* 同步执行,因此池是一个透明的空包装。小游戏平台上若要真 Worker,请用脚本模式:
|
||||||
|
* `new WorkerPool('workers/my-task/index.js')`——池会通过 `minigame.createWorker`
|
||||||
|
* 从预打包脚本创建 Worker(参见构造函数与随附模板)。
|
||||||
|
*
|
||||||
|
* 对于*真正可并行*平台上的 *CPU 密集型*负载,可将 [[getOptimalWorkerCount]] 作为 `maxWorkers` 传入,
|
||||||
|
* 跨可用核心并行(给主线程留一个核心)。注意:只有当你*同时*提交多个独立任务时 `maxWorkers` 才起作用——
|
||||||
|
* 单个排队任务始终只用一个 Worker。
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* Function mode (Web real-parallel; mini-game / native transparent sync fallback):
|
||||||
|
* ```ts
|
||||||
|
* const pool = new WorkerPool((n: number) => {
|
||||||
|
* let acc = 0;
|
||||||
|
* for (let i = 0; i < n; i++) acc += Math.sqrt(i);
|
||||||
|
* return acc;
|
||||||
|
* }, { maxWorkers: getOptimalWorkerCount(), idleReleaseAfter: 1000 });
|
||||||
|
*
|
||||||
|
* const result = await pool.run([1_000_000]);
|
||||||
|
* // ...
|
||||||
|
* pool.terminate();
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* Script mode (a real worker on Web AND every mini-game platform that has one):
|
||||||
|
* ```ts
|
||||||
|
* // Backend chain resolved at construction: platform worker (only when fully set up — see
|
||||||
|
* // checkWorkerScript) → global Worker → single-threaded via options.fallback → run() rejects.
|
||||||
|
* // Pool size is auto-capped by the platform: 1 worker on the seven single-worker platforms and
|
||||||
|
* // WeChat V1; up to maxWorkers on WeChat V2 and Web.
|
||||||
|
* // On WeChat V2 pass an explicit maxWorkers to scale beyond 1 (core count is not detectable there).
|
||||||
|
* const pool = new WorkerPool('workers/heavy-compute/index.js', {
|
||||||
|
* maxWorkers: 4,
|
||||||
|
* // Optional: same computation as the worker script's runTask(args), used single-threaded
|
||||||
|
* // when no worker backend is available at all. Without it, run() would reject there.
|
||||||
|
* fallback: (n: number) => { let acc = 0; for (let i = 0; i < n; i++) acc += Math.sqrt(i); return acc; },
|
||||||
|
* });
|
||||||
|
* const result = await pool.run([1_000_000]);
|
||||||
|
* pool.terminate();
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class WorkerPool {
|
||||||
|
private readonly _fn: WorkerTask | null;
|
||||||
|
private readonly _script: string | null;
|
||||||
|
private readonly _fallback: WorkerTask | null;
|
||||||
|
private readonly _idleReleaseAfter: number;
|
||||||
|
private readonly _timeout: number;
|
||||||
|
private readonly _explicitMax: number;
|
||||||
|
private _maxWorkers: number;
|
||||||
|
/** Execution state only; platform selection and identity belong to PAL. */
|
||||||
|
private _executionMode: WorkerExecutionMode;
|
||||||
|
private _activeBackend: IPlatformWorkerBackend | null = null;
|
||||||
|
/** Changes only on recheck; runtime degradation stays in the same recovery generation. */
|
||||||
|
private _backendGeneration = 0;
|
||||||
|
private _scriptFailureHint = '';
|
||||||
|
private _backendReason: string;
|
||||||
|
private _workers: PooledWorker[] = [];
|
||||||
|
private _queue: PoolTask[] = [];
|
||||||
|
private _released = false;
|
||||||
|
private _draining = false;
|
||||||
|
private _taskId = 0;
|
||||||
|
/**
|
||||||
|
* @en Consecutive infrastructure failures on the real worker backend. Reset by [[WorkerPool.recheck]].
|
||||||
|
* Reaching [[DEGRADE_AFTER_FAILURES]] triggers degradation to single-threaded sync execution.
|
||||||
|
* @zh 真 Worker 后端上累计的基础设施失败次数。[[WorkerPool.recheck]] 会重置;达到
|
||||||
|
* [[DEGRADE_AFTER_FAILURES]] 即触发降级为单线程同步执行。
|
||||||
|
*/
|
||||||
|
private _infraFailures = 0;
|
||||||
|
/** @en Whether this pool has degraded to single-threaded sync execution. @zh 本池是否已降级为单线程同步执行。 */
|
||||||
|
private _degraded = false;
|
||||||
|
/** @en Guards against spamming the degradation warning (warn at most once per pool). @zh 防止重复刷降级警告(每池至多警告一次)。 */
|
||||||
|
private _degradeWarned = false;
|
||||||
|
/**
|
||||||
|
* @en Guards the CONSTRUCTION-time degradation warning (at most once per pool, even across
|
||||||
|
* [[WorkerPool.recheck]] re-resolutions). @zh 防止重复刷**构造期**降级警告(每池至多一次,即便
|
||||||
|
* [[WorkerPool.recheck]] 反复重解析)。
|
||||||
|
*/
|
||||||
|
private _constructionWarned = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Create a pool from a self-contained function or a packaged script path.
|
||||||
|
* PAL selects a usable script backend and its concurrency limit. When no backend is
|
||||||
|
* available, script tasks use options.fallback; without it, run() rejects with PAL's reason.
|
||||||
|
* Function tasks use a worker when PAL supports them, otherwise they execute inline.
|
||||||
|
* Scripts receive `{ id, args }` and reply with `{ id, ok, value }` or `{ id, ok: false, error }`.
|
||||||
|
* @zh
|
||||||
|
* 使用独立函数或已打包的脚本路径创建任务池。脚本后端的选择和并发上限由 PAL 提供。
|
||||||
|
* 没有可用后端时,脚本任务执行 options.fallback;未提供则携带 PAL 的诊断原因拒绝任务。
|
||||||
|
* 函数任务在 PAL 支持时使用 Worker,否则在主线程执行。
|
||||||
|
* 脚本接收 `{ id, args }`,回复 `{ id, ok, value }` 或 `{ id, ok: false, error }`。
|
||||||
|
*/
|
||||||
|
constructor (fnOrScript: WorkerTask | string, options?: WorkerPoolOptions) {
|
||||||
|
const isScriptMode = typeof fnOrScript === 'string';
|
||||||
|
if (isScriptMode) {
|
||||||
|
if (!fnOrScript) {
|
||||||
|
throw new TypeError(getError(16500));
|
||||||
|
}
|
||||||
|
this._script = fnOrScript;
|
||||||
|
this._fn = null;
|
||||||
|
} else {
|
||||||
|
if (typeof fnOrScript !== 'function') {
|
||||||
|
throw new TypeError(getError(16501));
|
||||||
|
}
|
||||||
|
this._fn = fnOrScript;
|
||||||
|
this._script = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawFallback = options ? options.fallback : undefined;
|
||||||
|
this._fallback = typeof rawFallback === 'function' ? rawFallback : null;
|
||||||
|
|
||||||
|
const rawMax = options ? options.maxWorkers : undefined;
|
||||||
|
// An explicit, valid pool size (>= 1). 0 means "not specified" so we can apply a default below.
|
||||||
|
this._explicitMax = (typeof rawMax === 'number' && Number.isFinite(rawMax) && rawMax >= 1)
|
||||||
|
? Math.floor(rawMax)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
const rawTimeout = options ? options.timeout : undefined;
|
||||||
|
this._timeout = (typeof rawTimeout === 'number' && Number.isFinite(rawTimeout) && rawTimeout > 0)
|
||||||
|
? rawTimeout
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// Use `??` so an explicit `0` (meaning "never release idle workers") is preserved.
|
||||||
|
this._idleReleaseAfter = (options && options.idleReleaseAfter !== undefined)
|
||||||
|
? options.idleReleaseAfter
|
||||||
|
: 1000;
|
||||||
|
|
||||||
|
this._executionMode = 'none';
|
||||||
|
this._backendReason = '';
|
||||||
|
this._maxWorkers = 0;
|
||||||
|
this._resolveBackend();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* (Re-)resolve which execution backend this pool uses, and cap the pool size accordingly.
|
||||||
|
*
|
||||||
|
* Split out of the constructor so [[WorkerPool.recheck]] can run it again later. Resolution is
|
||||||
|
* driven purely by runtime capability, never by a compile-time platform constant — branching on
|
||||||
|
* `WECHAT` is what left seven mini-game platforms with a working `createWorker` falling through to
|
||||||
|
* synchronous execution.
|
||||||
|
* @zh
|
||||||
|
* (重新)解析本池使用哪个执行后端,并据此封顶池大小。
|
||||||
|
*
|
||||||
|
* 从构造函数中拆出,以便 [[WorkerPool.recheck]] 之后能再次调用。解析完全由**运行时能力**驱动,
|
||||||
|
* 绝不依赖编译期平台常量——正是对 `WECHAT` 的分支判断,让 7 个拥有可用 `createWorker` 的
|
||||||
|
* 小游戏平台掉进了同步执行。
|
||||||
|
*/
|
||||||
|
private _resolveBackend (): void {
|
||||||
|
const platform = getWorkerBackend();
|
||||||
|
const explicitMax = this._explicitMax;
|
||||||
|
const desired = explicitMax > 0 ? explicitMax : getOptimalWorkerCount();
|
||||||
|
this._activeBackend = null;
|
||||||
|
this._scriptFailureHint = platform.scriptFailureHint;
|
||||||
|
this._backendReason = '';
|
||||||
|
|
||||||
|
if (this._script) {
|
||||||
|
const resolved = platform.resolveScriptWorker(this._script);
|
||||||
|
if (resolved.backend) {
|
||||||
|
this._executionMode = 'worker';
|
||||||
|
this._activeBackend = resolved.backend;
|
||||||
|
this._scriptFailureHint = resolved.backend.scriptFailureHint;
|
||||||
|
this._maxWorkers = Math.min(desired, resolved.backend.concurrencyLimit);
|
||||||
|
} else if (this._fallback) {
|
||||||
|
this._executionMode = 'sync';
|
||||||
|
this._maxWorkers = 1;
|
||||||
|
this._warnConstructionDegrade(resolved.warnOnFailure, resolved.diagnosis.reason);
|
||||||
|
} else {
|
||||||
|
this._executionMode = 'none';
|
||||||
|
this._maxWorkers = 0;
|
||||||
|
this._backendReason = getError(16504, this._script, resolved.diagnosis.reason);
|
||||||
|
this._warnConstructionDegrade(resolved.warnOnFailure, resolved.diagnosis.reason);
|
||||||
|
}
|
||||||
|
} else if (platform.supportsFunctionWorker) {
|
||||||
|
this._executionMode = 'worker';
|
||||||
|
this._activeBackend = platform;
|
||||||
|
this._maxWorkers = Math.min(explicitMax > 0 ? explicitMax : 1, platform.concurrencyLimit);
|
||||||
|
} else {
|
||||||
|
this._executionMode = 'sync';
|
||||||
|
this._maxWorkers = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Re-probe the platform and re-resolve the execution backend.
|
||||||
|
*
|
||||||
|
* The backend is normally decided once, at construction. That is wrong whenever capability appears
|
||||||
|
* LATER, which really happens:
|
||||||
|
* - the worker script lives in a WeChat subpackage that finishes downloading after the pool was
|
||||||
|
* created — `diagnose()` failed at construction because the file did not exist yet;
|
||||||
|
* - the base library hot-updates, or `wx.env.isSupportStandardWorker` flips as the V2 grey release
|
||||||
|
* rolls out to the device.
|
||||||
|
*
|
||||||
|
* Without this, a pool that probed too early stays locked to `'sync'`/`'none'` for its entire
|
||||||
|
* lifetime even though a real worker is now available.
|
||||||
|
*
|
||||||
|
* Idle executors are retired; busy executors finish their current task and are then retired.
|
||||||
|
* Queued tasks use the newly selected backend, or reject if it is unavailable without a fallback.
|
||||||
|
* Transferred tasks cannot be replayed after failure because ownership has already moved.
|
||||||
|
*
|
||||||
|
* @returns the execution state: `'worker'`, `'sync'` or `'none'`.
|
||||||
|
* @zh
|
||||||
|
* 重新探测平台并重新解析执行后端。
|
||||||
|
*
|
||||||
|
* 后端通常只在构造时决定一次。但只要能力是**之后**才出现的,这就错了,而这确实会发生:
|
||||||
|
* - worker 脚本位于微信分包中,该分包在池创建之后才下载完成——构造时 `diagnose()` 因文件尚不存在而失败;
|
||||||
|
* - 基础库热更新,或随着 V2 灰度推送到该设备,`wx.env.isSupportStandardWorker` 发生翻转。
|
||||||
|
*
|
||||||
|
* 没有这个入口,探测过早的池会在整个生命周期里被锁死在 `'sync'`/`'none'` 上,
|
||||||
|
* 即便真 Worker 现在已经可用。
|
||||||
|
*
|
||||||
|
* 空闲执行器立即释放,忙碌执行器完成当前任务后释放。排队任务交给新后端;
|
||||||
|
* 若新后端不可用且没有 fallback,则拒绝排队任务。已移交所有权的任务失败后不能重放。
|
||||||
|
*
|
||||||
|
* @returns 当前执行状态:`'worker'`、`'sync'` 或 `'none'`。
|
||||||
|
*/
|
||||||
|
public recheck (): WorkerExecutionMode {
|
||||||
|
if (this._released) {
|
||||||
|
return this.backend;
|
||||||
|
}
|
||||||
|
// Give the real worker backend another chance: a subpackage may have finished downloading or
|
||||||
|
// the base library may have hot-updated since we degraded. Reset the failure budget so the
|
||||||
|
// fresh probe starts clean. (_degradeWarned stays sticky to avoid log spam across rechecks.)
|
||||||
|
this._infraFailures = 0;
|
||||||
|
this._degraded = false;
|
||||||
|
// Drop the cached platform probe so the next read reflects the current environment.
|
||||||
|
resetWorkerBackendCache();
|
||||||
|
this._resolveBackend();
|
||||||
|
this._backendGeneration++;
|
||||||
|
|
||||||
|
// New tasks must use the newly resolved backend. Busy workers finish their current
|
||||||
|
// task, but are never reused after this capability check.
|
||||||
|
this._retireWorkers();
|
||||||
|
this._drain();
|
||||||
|
return this.backend;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _retireWorkers (): void {
|
||||||
|
for (let i = this._workers.length - 1; i >= 0; i--) {
|
||||||
|
const worker = this._workers[i];
|
||||||
|
worker.retired = true;
|
||||||
|
if (!worker.busy) {
|
||||||
|
this._workers.splice(i, 1);
|
||||||
|
worker.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Current execution state: worker, synchronous fallback, or unavailable.
|
||||||
|
* @zh 当前执行状态:Worker、主线程同步回退,或不可用。
|
||||||
|
*/
|
||||||
|
public get backend (): WorkerExecutionMode {
|
||||||
|
return this._executionMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* The resolved parallel worker count this pool will actually run tasks on
|
||||||
|
* (already clamped by the platform concurrency limit and the hardware estimate).
|
||||||
|
* Callers doing manual chunking should size their chunk count to this value so that chunks map
|
||||||
|
* 1:1 onto real parallel workers, instead of queueing serially on a single worker (e.g. WeChat V1,
|
||||||
|
* where `concurrencyLimit` is 1) and multiplying the per-frame round-trip latency.
|
||||||
|
* @zh
|
||||||
|
* 池实际会用于并行执行任务的 worker 数(已计入平台并发上限与硬件核数估计)。
|
||||||
|
* 手动分块的调用方应按此值确定分块数,使分块与真实并行 worker 一一对应;否则在单 worker 平台
|
||||||
|
* (如微信 V1,`concurrencyLimit` 为 1)上多块会串行排队,成倍放大每帧往返延迟。
|
||||||
|
*/
|
||||||
|
public get concurrency (): number {
|
||||||
|
return this._maxWorkers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Queue a task and resolve with its return value when it completes.
|
||||||
|
* If a worker is free (or the pool is under `maxWorkers`), the task starts immediately;
|
||||||
|
* otherwise it waits in the queue.
|
||||||
|
* @zh
|
||||||
|
* 排队一个任务,完成时用其返回值 resolve。
|
||||||
|
* 如果有空闲 Worker(或池中 Worker 数未达到 `maxWorkers`),任务立即开始;否则在队列中等待。
|
||||||
|
* @param args Arguments passed to the task function. 传给任务函数的参数。
|
||||||
|
* @param transfer Transferable objects to transfer to the worker. 零拷贝转移到 Worker 的对象。
|
||||||
|
*/
|
||||||
|
public run<TResult = unknown> (args?: unknown[], transfer?: Transferable[]): Promise<TResult> {
|
||||||
|
return new Promise<TResult>((resolve, reject) => {
|
||||||
|
if (this._released) {
|
||||||
|
reject(new Error(getError(16502)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this._executionMode === 'none') {
|
||||||
|
// Script mode, but no worker backend is available (WeChat worker not fully set up,
|
||||||
|
// no global Worker) and no options.fallback was provided — we cannot proceed.
|
||||||
|
reject(new Error(this._backendReason || getError(16503)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._queue.push({
|
||||||
|
args: args || [],
|
||||||
|
transfer: transfer || [],
|
||||||
|
resolve: (value: unknown): void => resolve(value as TResult),
|
||||||
|
reject,
|
||||||
|
});
|
||||||
|
this._drain();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Terminate all workers immediately and reject all pending tasks.
|
||||||
|
* @zh
|
||||||
|
* 立即终止所有 Worker,并拒绝所有排队中的任务。
|
||||||
|
*/
|
||||||
|
public terminate (): void {
|
||||||
|
if (this._released) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._released = true;
|
||||||
|
|
||||||
|
const error = new Error(getError(16502));
|
||||||
|
for (const task of this._queue) {
|
||||||
|
task.reject(error);
|
||||||
|
}
|
||||||
|
this._queue.length = 0;
|
||||||
|
|
||||||
|
for (const w of this._workers) {
|
||||||
|
w.dispose();
|
||||||
|
}
|
||||||
|
this._workers.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _drain (): void {
|
||||||
|
if (this._released || this._draining) return;
|
||||||
|
this._draining = true;
|
||||||
|
try {
|
||||||
|
if (this._executionMode === 'none') {
|
||||||
|
const pending = this._queue.splice(0);
|
||||||
|
for (const task of pending) task.reject(new Error(this._backendReason));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
while (this._queue.length > 0) {
|
||||||
|
let worker = this._findIdleWorker();
|
||||||
|
if (!worker && this._workers.length < this._maxWorkers) {
|
||||||
|
try {
|
||||||
|
worker = this._spawnWorker();
|
||||||
|
} catch (err) {
|
||||||
|
// Script-mode worker creation can throw synchronously (e.g. the path is not
|
||||||
|
// packaged into the `workers` directory, or a subpackage has not been downloaded).
|
||||||
|
// Treat it as an infrastructure failure: degrade so we stop respawning a broken
|
||||||
|
// backend, and re-run this task via the fallback when one exists (otherwise reject
|
||||||
|
// it). Keep draining either way so the remaining tasks are not left hanging.
|
||||||
|
const failed = this._queue.shift();
|
||||||
|
this._onInfraFailure(failed || null, err as Error);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (worker) {
|
||||||
|
this._workers.push(worker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!worker) {
|
||||||
|
// No free worker and already at maxWorkers: wait for a completion callback.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const task = this._queue.shift();
|
||||||
|
if (task) {
|
||||||
|
this._dispatch(worker, task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this._draining = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _findIdleWorker (): PooledWorker | null {
|
||||||
|
for (const w of this._workers) {
|
||||||
|
if (!w.busy && !w.retired) {
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _spawnWorker (): PooledWorker {
|
||||||
|
const generation = this._backendGeneration;
|
||||||
|
let worker: IWorker | null = null;
|
||||||
|
let fn = this._fn;
|
||||||
|
if (this._script) {
|
||||||
|
if (this._executionMode === 'worker') {
|
||||||
|
// Use the exact backend PAL selected, so creation matches its concurrency and capabilities.
|
||||||
|
worker = this._activeBackend!.createScriptWorker(this._script);
|
||||||
|
} else {
|
||||||
|
// 'sync' backend (no worker at all): run the user-provided fallback inline.
|
||||||
|
// ('none' never reaches here — run() rejects before queuing.)
|
||||||
|
fn = this._fallback;
|
||||||
|
}
|
||||||
|
} else if (this._executionMode === 'worker') {
|
||||||
|
worker = this._activeBackend!.createFunctionWorker(this._fn!);
|
||||||
|
if (!worker) {
|
||||||
|
// Capability disappeared before creation. Do not silently report a worker pool
|
||||||
|
// while scheduling multiple inline executors.
|
||||||
|
this._executionMode = 'sync';
|
||||||
|
this._maxWorkers = 1;
|
||||||
|
this._retireWorkers();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A null `worker` leaves PooledWorker in inline mode → it runs `fn` synchronously.
|
||||||
|
const pooled = new PooledWorker(worker, fn, this._idleReleaseAfter, this._onWorkerIdle.bind(this), this._timeout);
|
||||||
|
// Route infrastructure failures (timeout / onError / malformed reply) on a REAL worker back to
|
||||||
|
// the pool so it can count them and degrade to single-threaded execution instead of hanging.
|
||||||
|
// An inline executor never triggers it, so the callback simply stays unused there.
|
||||||
|
pooled.onInfraFailure = (t: PoolTask, err: Error): void => {
|
||||||
|
// Only faults from before recheck belong to an obsolete backend. Workers retired
|
||||||
|
// by degradation still recover non-transferred tasks in the current generation.
|
||||||
|
if (generation !== this._backendGeneration) t.reject(err);
|
||||||
|
else this._onInfraFailure(t, err);
|
||||||
|
};
|
||||||
|
return pooled;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _dispatch (worker: PooledWorker, task: PoolTask): void {
|
||||||
|
worker.busy = true;
|
||||||
|
worker.cancelIdleTimer();
|
||||||
|
const id = ++this._taskId;
|
||||||
|
worker.onComplete = (): void => {
|
||||||
|
worker.busy = false;
|
||||||
|
if (worker.retired) this._onWorkerIdle(worker);
|
||||||
|
else this._drain();
|
||||||
|
};
|
||||||
|
// Once ownership has been transferred, the original arguments cannot be replayed safely.
|
||||||
|
task.transferred = !worker.isInline && !!this._activeBackend?.supportsTransfer && task.transfer.length > 0;
|
||||||
|
worker.execute(id, task);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _onWorkerIdle (worker: PooledWorker): void {
|
||||||
|
if (this._released) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (worker.busy) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const idx = this._workers.indexOf(worker);
|
||||||
|
if (idx < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._workers.splice(idx, 1);
|
||||||
|
worker.dispose();
|
||||||
|
// A worker was freed up (idle-release or failure): re-drain so queued tasks don't stall.
|
||||||
|
this._drain();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* Handle an INFRASTRUCTURE failure on a real worker: it timed out, errored, failed to spawn, or
|
||||||
|
* spoke a malformed protocol. These all mean the worker backend is not functioning for this
|
||||||
|
* script — unlike a task-level `{ ok: false }` reply (a genuine computation error), which is
|
||||||
|
* rejected directly and never reaches here.
|
||||||
|
*
|
||||||
|
* Script mode: count the failure and, once [[DEGRADE_AFTER_FAILURES]] is reached, degrade the
|
||||||
|
* WHOLE pool so no further task hangs on the broken backend. With `options.fallback` we switch to
|
||||||
|
* the `'sync'` backend (one inline executor on the main thread) and re-run the failed task through
|
||||||
|
* it, so the caller still gets a result instead of a rejection — the graceful "warn + run
|
||||||
|
* single-threaded" path the engine promises. Without a fallback there is no single-thread path to
|
||||||
|
* degrade to, so we keep the existing evict-and-respawn recovery and reject the task, but warn
|
||||||
|
* loudly so the developer learns the worker is broken and how to fix it.
|
||||||
|
*
|
||||||
|
* Function mode is deliberately EXCLUDED from degradation: its inline path is the SAME `_fn` that
|
||||||
|
* may have just deadlocked inside the worker, so running it on the main thread could move the hang
|
||||||
|
* onto the render thread. There we keep the existing recovery — reject the task, evict, respawn.
|
||||||
|
*
|
||||||
|
* @param task The in-flight task that failed, or `null` when the failure carries no task.
|
||||||
|
* @param error The infrastructure error.
|
||||||
|
*/
|
||||||
|
private _onInfraFailure (task: PoolTask | null, error: Error): void {
|
||||||
|
if (!this._script) {
|
||||||
|
// Function mode: no safe single-thread path (see above). Reject and let _settle evict +
|
||||||
|
// respawn a fresh worker, exactly as before the circuit breaker existed.
|
||||||
|
if (task) {
|
||||||
|
task.reject(error);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._infraFailures++;
|
||||||
|
if (!this._degraded && this._infraFailures >= DEGRADE_AFTER_FAILURES) {
|
||||||
|
this._degraded = true;
|
||||||
|
if (this._fallback) {
|
||||||
|
// Graceful degradation: every future task runs on the main thread via the fallback.
|
||||||
|
this._executionMode = 'sync';
|
||||||
|
this._backendReason = '';
|
||||||
|
this._maxWorkers = 1;
|
||||||
|
// Drop idle real workers so the next dispatch goes to an inline executor, not a
|
||||||
|
// leftover worker on the backend we just gave up on.
|
||||||
|
this._retireWorkers();
|
||||||
|
}
|
||||||
|
this._warnDegrade(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!task) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this._executionMode === 'sync' && this._fallback && !task.transferred) {
|
||||||
|
// Re-run the failed task on the main thread. Front of the queue preserves ordering; the
|
||||||
|
// eviction-driven re-drain (runtime failure) or the _drain loop (spawn failure) dispatches
|
||||||
|
// it through an inline executor running the fallback.
|
||||||
|
this._queue.unshift(task);
|
||||||
|
} else {
|
||||||
|
task.reject(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* Emit the one-time RUNTIME-degradation warning. `_degradeWarned` is sticky for the pool's
|
||||||
|
* lifetime so repeated failures — or a `recheck()` that re-degrades — never spam the log.
|
||||||
|
*/
|
||||||
|
private _warnDegrade (error: Error): void {
|
||||||
|
if (this._degradeWarned) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._degradeWarned = true;
|
||||||
|
const script = this._script || '(function)';
|
||||||
|
warnID(this._fallback ? 16505 : 16506, script, error.message, this._scriptFailureHint);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PAL decides whether unavailable script execution deserves a one-time warning. */
|
||||||
|
private _warnConstructionDegrade (warnOnFailure: boolean, reason: string): void {
|
||||||
|
if (!warnOnFailure || this._constructionWarned) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._constructionWarned = true;
|
||||||
|
warnID(this._fallback ? 16507 : 16508, this._script || '(function)', reason, this._scriptFailureHint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
interface PoolTask {
|
||||||
|
args: unknown[];
|
||||||
|
transfer: Transferable[];
|
||||||
|
transferred?: boolean;
|
||||||
|
resolve: (value: unknown) => void;
|
||||||
|
reject: (reason?: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* A single pooled worker, either backed by a real Web Worker or an inline synchronous executor.
|
||||||
|
*/
|
||||||
|
class PooledWorker {
|
||||||
|
public busy = false;
|
||||||
|
public retired = false;
|
||||||
|
public onComplete: (() => void) | null = null;
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* Set by the pool: called when an INFRASTRUCTURE failure occurs while a task is in flight — the
|
||||||
|
* worker timed out, errored, or spoke a malformed protocol. The pool counts these and (in script
|
||||||
|
* mode) degrades to single-threaded execution so nothing hangs. Deliberately distinct from a
|
||||||
|
* task-level `{ ok: false }` reply (a genuine computation error), which is rejected directly and
|
||||||
|
* never routed here. Only real workers ever trigger it; an inline executor cannot suffer an
|
||||||
|
* infrastructure failure (a throwing `fallback`/`_fn` is a task-level error).
|
||||||
|
*/
|
||||||
|
public onInfraFailure: ((task: PoolTask, error: Error) => void) | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Whether this pooled worker runs tasks INLINE on the calling thread instead of owning a real
|
||||||
|
* worker. True for the `'sync'` backend and for function mode on platforms that cannot rebuild a
|
||||||
|
* function from source. Such an executor is a placeholder, not parallelism — [[WorkerPool.recheck]]
|
||||||
|
* retires the idle ones once a real backend appears.
|
||||||
|
* @zh
|
||||||
|
* 本池化 worker 是否在调用线程上**内联**执行任务,而非持有真正的 worker。
|
||||||
|
* `'sync'` 后端、以及无法从源码重建函数的平台上的函数模式均如此。这类执行器只是占位而非并行——
|
||||||
|
* 一旦真后端出现,[[WorkerPool.recheck]] 会把其中空闲的退役。
|
||||||
|
*/
|
||||||
|
public get isInline (): boolean {
|
||||||
|
return this._worker === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly _worker: IWorker | null;
|
||||||
|
private readonly _fn: WorkerTask | null;
|
||||||
|
private readonly _idleReleaseAfter: number;
|
||||||
|
private readonly _timeout: number;
|
||||||
|
private readonly _onIdle: (worker: PooledWorker) => void;
|
||||||
|
private _current: PoolTask | null = null;
|
||||||
|
private _currentId = -1;
|
||||||
|
private _idleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private _timeoutTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private _disposed = false;
|
||||||
|
private _failed = false;
|
||||||
|
|
||||||
|
constructor (
|
||||||
|
worker: IWorker | null,
|
||||||
|
fn: WorkerTask | null,
|
||||||
|
idleReleaseAfter: number,
|
||||||
|
onIdle: (worker: PooledWorker) => void,
|
||||||
|
timeout = 0,
|
||||||
|
) {
|
||||||
|
this._worker = worker;
|
||||||
|
this._fn = fn;
|
||||||
|
this._idleReleaseAfter = idleReleaseAfter;
|
||||||
|
this._onIdle = onIdle;
|
||||||
|
this._timeout = timeout > 0 ? timeout : 0;
|
||||||
|
|
||||||
|
if (worker) {
|
||||||
|
// IWorker.onMessage hands back the reply payload directly (the adapter unwraps `e.data`
|
||||||
|
// on Web, and WeChat's `onMessage` already passes `res`), so no MessageEvent here.
|
||||||
|
worker.onMessage((reply: IWorkerReply): void => {
|
||||||
|
this._onMessage(reply);
|
||||||
|
});
|
||||||
|
worker.onError((e: any): void => {
|
||||||
|
this._failed = true;
|
||||||
|
if (this._current) {
|
||||||
|
// Busy: fail the in-flight task; _settle's `_failed` branch then evicts us.
|
||||||
|
this._settle(null, new Error(e && e.message ? String(e.message) : getError(16509)));
|
||||||
|
} else {
|
||||||
|
// Idle: there is no task to settle, but this worker is no longer trustworthy.
|
||||||
|
// It MUST be evicted here — otherwise it stays in the pool with `busy === false`,
|
||||||
|
// the next task gets dispatched onto it, and `postMessage` goes into a black hole
|
||||||
|
// (the task hangs forever, and script mode has no timeout to recover it).
|
||||||
|
// Real triggers: an uncaught async error inside the worker (e.g. a `setInterval`
|
||||||
|
// callback throwing), or WeChat killing the worker process (`onProcessKilled`).
|
||||||
|
this._evict();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public execute (id: number, task: PoolTask): void {
|
||||||
|
this._current = task;
|
||||||
|
this._currentId = id;
|
||||||
|
if (!this._worker) {
|
||||||
|
if (!this._fn) {
|
||||||
|
// Script mode without a live worker should never reach here (run()/_drain guard it),
|
||||||
|
// but stay defensive: there is no function to run synchronously, so fail the task.
|
||||||
|
this._settle(null, new Error(getError(16510)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Inline synchronous fallback (non-Worker platforms, function mode only). This blocks the
|
||||||
|
// main thread, which is the unavoidable behavior when no worker is available.
|
||||||
|
try {
|
||||||
|
const value = this._fn(...task.args);
|
||||||
|
this._settle(value, null);
|
||||||
|
} catch (err) {
|
||||||
|
this._settle(null, err as Error);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Arm before sending: adapters may synchronously report an error (or a test reply).
|
||||||
|
this.armTimeout();
|
||||||
|
try {
|
||||||
|
this._worker.postMessage({ id, args: task.args }, task.transfer);
|
||||||
|
} catch (err) {
|
||||||
|
this._failed = true;
|
||||||
|
this._settle(null, err instanceof Error ? err : new Error(String(err)));
|
||||||
|
}
|
||||||
|
// Watchdog. Only meaningful for a REAL worker: the inline synchronous path above blocks the
|
||||||
|
// main thread for the whole duration, so a timer could never fire during it anyway.
|
||||||
|
// Without this, a worker that accepts the message and never replies — a script that deadlocks,
|
||||||
|
// an infinite loop, a platform that silently drops the message — leaves the task pending
|
||||||
|
// forever AND leaves that worker parked in the pool with `busy === true`, permanently
|
||||||
|
// shrinking the pool's effective size by one on every occurrence.
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* Start the per-task watchdog. On expiry the task is failed and this worker is EVICTED (not
|
||||||
|
* merely marked free): an unresponsive worker is indistinguishable from a dead one, so letting
|
||||||
|
* the pool reuse it would just hang the next task too. Eviction routes through `_onIdle`, which
|
||||||
|
* splices us out, disposes us and re-drains the queue onto a freshly spawned worker.
|
||||||
|
*/
|
||||||
|
private armTimeout (): void {
|
||||||
|
if (this._timeout <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.cancelTimeoutTimer();
|
||||||
|
const id = this._currentId;
|
||||||
|
this._timeoutTimer = setTimeout(() => {
|
||||||
|
this._timeoutTimer = null;
|
||||||
|
// Ignore a timer that outlived its task (shouldn't happen — _settle cancels it — but a
|
||||||
|
// stale timer firing against a NEW task would fail an innocent one).
|
||||||
|
if (!this._current || this._currentId !== id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._failed = true;
|
||||||
|
this._settle(null, new Error(getError(16511, this._timeout)));
|
||||||
|
}, this._timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
private cancelTimeoutTimer (): void {
|
||||||
|
if (this._timeoutTimer !== null) {
|
||||||
|
clearTimeout(this._timeoutTimer);
|
||||||
|
this._timeoutTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public cancelIdleTimer (): void {
|
||||||
|
if (this._idleTimer !== null) {
|
||||||
|
clearTimeout(this._idleTimer);
|
||||||
|
this._idleTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public dispose (): void {
|
||||||
|
if (this._disposed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._disposed = true;
|
||||||
|
this.cancelIdleTimer();
|
||||||
|
this.cancelTimeoutTimer();
|
||||||
|
if (this._worker) {
|
||||||
|
this._worker.terminate();
|
||||||
|
}
|
||||||
|
if (this._current) {
|
||||||
|
this._current.reject(new Error(getError(16512)));
|
||||||
|
this._current = null;
|
||||||
|
this._currentId = -1;
|
||||||
|
}
|
||||||
|
this.onComplete = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _onMessage (reply: IWorkerReply): void {
|
||||||
|
if (!this._current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Boundary check: the worker script must speak the engine protocol. A malformed reply means
|
||||||
|
// the packaged file is wrong (not based on the template) — fail loudly with a clear error
|
||||||
|
// instead of letting the task hang forever waiting for a well-formed reply.
|
||||||
|
if (!reply || typeof reply !== 'object'
|
||||||
|
|| typeof reply.id !== 'number'
|
||||||
|
|| typeof reply.ok !== 'boolean') {
|
||||||
|
this._failed = true;
|
||||||
|
this._settle(null, new Error(getError(16513)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Guard against a stale/late reply from a previous task on the same worker.
|
||||||
|
if (reply.id !== this._currentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (reply.ok) {
|
||||||
|
this._settle(reply.value, null);
|
||||||
|
} else {
|
||||||
|
this._settle(null, new Error(reply.error || getError(16514)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _settle (value: unknown, error: Error | null): void {
|
||||||
|
const task = this._current;
|
||||||
|
if (!task) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this._current = null;
|
||||||
|
this._currentId = -1;
|
||||||
|
this.cancelTimeoutTimer();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
if (this._failed && this.onInfraFailure) {
|
||||||
|
// Infrastructure failure (timeout / onError / malformed reply): the worker backend
|
||||||
|
// itself is not functioning. Hand the task to the pool, which counts the failure,
|
||||||
|
// degrades script-mode pools to single-threaded execution once the threshold is hit,
|
||||||
|
// and either re-runs this task via the fallback or rejects it.
|
||||||
|
this.onInfraFailure(task, error);
|
||||||
|
} else {
|
||||||
|
// Task-level failure (the worker replied { ok: false }, or an inline fallback/_fn
|
||||||
|
// threw): a genuine computation error, not a broken backend. Reject directly and keep
|
||||||
|
// trusting the worker.
|
||||||
|
task.reject(error);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
task.resolve(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A worker that reported an uncaught error is not trustworthy for reuse: dispose it so the
|
||||||
|
// pool spawns a fresh one instead of replaying the same failure on every task.
|
||||||
|
if (this._failed) {
|
||||||
|
this._evict();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark idle (kicking off the idle-release timer) and notify the pool to drain the queue.
|
||||||
|
if (this._idleReleaseAfter > 0 && !this._disposed) {
|
||||||
|
this.cancelIdleTimer();
|
||||||
|
this._idleTimer = setTimeout(() => {
|
||||||
|
this._idleTimer = null;
|
||||||
|
this._onIdle(this);
|
||||||
|
}, this._idleReleaseAfter);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.onComplete) {
|
||||||
|
const cb = this.onComplete;
|
||||||
|
this.onComplete = null;
|
||||||
|
cb();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* Retire this worker for good: drop any completion callback, clear the busy flag, and hand
|
||||||
|
* ourselves to the pool's idle hook (which splices us out of `_workers`, calls `dispose()` and
|
||||||
|
* re-drains the queue so queued tasks get a freshly spawned worker).
|
||||||
|
*
|
||||||
|
* Used by BOTH failure paths, which is the whole point of extracting it: `_settle`'s `_failed`
|
||||||
|
* branch (worker died while a task was in flight) and the idle `onError` branch (worker died
|
||||||
|
* while idle). The idle path can never reach the `_settle` branch, because `_settle` returns
|
||||||
|
* early when `_current` is null — routing it here is what stops a dead worker from silently
|
||||||
|
* swallowing the next task.
|
||||||
|
*/
|
||||||
|
private _evict (): void {
|
||||||
|
this.onComplete = null;
|
||||||
|
this.busy = false;
|
||||||
|
this._onIdle(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
interface IWorkerReply {
|
||||||
|
id: number;
|
||||||
|
ok: boolean;
|
||||||
|
value?: unknown;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,413 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2018-2023 Xiamen Yaji Software Co., Ltd.
|
||||||
|
|
||||||
|
http://www.cocos.com
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||||
|
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createWorkerBackend } from 'pal/worker';
|
||||||
|
import type { IWorker, IPlatformWorkerBackend, IWorkerCapabilities } from 'pal/worker';
|
||||||
|
import { getError } from '../core/platform/debug';
|
||||||
|
|
||||||
|
export type { IWorker };
|
||||||
|
|
||||||
|
let backend: IPlatformWorkerBackend | undefined;
|
||||||
|
|
||||||
|
/** @internal Shared by capability queries and WorkerPool. */
|
||||||
|
export function getWorkerBackend (): IPlatformWorkerBackend {
|
||||||
|
return backend || (backend = createWorkerBackend());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal Re-probe PAL when a pool explicitly rechecks its capabilities. */
|
||||||
|
export function resetWorkerBackendCache (): void {
|
||||||
|
backend = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Current Worker capabilities reported by PAL.
|
||||||
|
* @zh PAL 提供的当前 Worker 能力。
|
||||||
|
*/
|
||||||
|
export function getWorkerCapabilities (): IWorkerCapabilities {
|
||||||
|
const current = getWorkerBackend();
|
||||||
|
return {
|
||||||
|
supportsStandardWorker: current.supportsStandardWorker,
|
||||||
|
available: current.concurrencyLimit > 0,
|
||||||
|
parallel: current.concurrencyLimit > 1,
|
||||||
|
concurrencyLimit: current.concurrencyLimit,
|
||||||
|
supportsTransfer: current.supportsTransfer,
|
||||||
|
supportsSharedArrayBuffer: current.supportsSharedArrayBuffer,
|
||||||
|
supportsFunctionWorker: current.supportsFunctionWorker,
|
||||||
|
reason: current.capabilityReason,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* The task function executed inside a Web Worker.
|
||||||
|
*
|
||||||
|
* **Important**: the function must be *self-contained*: it is serialized via `Function.prototype.toString()`
|
||||||
|
* and reconstructed in a fresh global scope inside the worker, so it cannot capture variables from the
|
||||||
|
* enclosing closure, nor reference any engine / scene objects (`Node`, `Component`, `Vec3`, ...).
|
||||||
|
* Only plain data (numbers, strings, arrays, plain objects) and transferable buffers (`ArrayBuffer`,
|
||||||
|
* typed arrays backed by their own buffer) may cross the worker boundary.
|
||||||
|
*
|
||||||
|
* @zh
|
||||||
|
* 在 Web Worker 内执行的任务函数。
|
||||||
|
*
|
||||||
|
* **注意**:函数必须*自包含*——引擎通过 `Function.prototype.toString()` 序列化函数并在 Worker 的全新全局作用域中重建,
|
||||||
|
* 因此它不能捕获外部闭包变量,也不能引用任何引擎 / 场景对象(`Node`、`Component`、`Vec3` 等)。
|
||||||
|
* 只有普通数据(数字、字符串、数组、普通对象)和可转移缓冲区(`ArrayBuffer`、自带缓冲区的类型化数组)可以跨 Worker 边界传递。
|
||||||
|
*
|
||||||
|
* @remarks
|
||||||
|
* @en
|
||||||
|
* The default argument type is `any[]` rather than `unknown[]`, deliberately. Arguments reach the task
|
||||||
|
* through a DYNAMIC array channel — `pool.run([1_000_000])` is `unknown[]`, spread internally as
|
||||||
|
* `fn(...args)` — so the type system can never relate what you pass to `run()` to what your task
|
||||||
|
* declares. An `unknown[]` parameter therefore buys zero safety while breaking the natural spelling:
|
||||||
|
* under `strictFunctionTypes` a concrete `(limit: number) => number` is NOT assignable to
|
||||||
|
* `(...args: unknown[]) => unknown`, so `new WorkerPool(fn, { fallback: countPrimes })` would not
|
||||||
|
* compile. `any[]` restores bivariance and lets the obvious code type-check. Pass explicit type
|
||||||
|
* arguments when you want the stricter shape: `WorkerTask<[number, number], number>`.
|
||||||
|
* @zh
|
||||||
|
* 默认参数类型刻意取 `any[]` 而非 `unknown[]`。参数是通过**动态数组通道**抵达任务函数的——
|
||||||
|
* `pool.run([1_000_000])` 是 `unknown[]`,内部以 `fn(...args)` 展开——因此类型系统永远无法把你传给
|
||||||
|
* `run()` 的东西与任务函数的声明关联起来。于是 `unknown[]` 参数**换不到任何安全性**,却破坏了最自然的写法:
|
||||||
|
* 在 `strictFunctionTypes` 下,具体的 `(limit: number) => number` **不能**赋值给
|
||||||
|
* `(...args: unknown[]) => unknown`,导致 `new WorkerPool(fn, { fallback: countPrimes })` 无法编译。
|
||||||
|
* `any[]` 恢复双变,让显而易见的代码通过类型检查。需要更严格的形状时请显式传类型参数:
|
||||||
|
* `WorkerTask<[number, number], number>`。
|
||||||
|
*/
|
||||||
|
// `any[]` here is a deliberate, documented trade-off — see the remarks above. Do not "fix" it back to
|
||||||
|
// `unknown[]`: that reintroduces a compile error on every concrete task function.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
export type WorkerTask<TArgs extends any[] = any[], TResult = unknown> = (...args: TArgs) => TResult;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Detect whether the current environment supports spawning a Web Worker from a serialized function
|
||||||
|
* (i.e. `Worker` constructor + `Blob` + `URL.createObjectURL` are all available).
|
||||||
|
*
|
||||||
|
* This is the capability required by **mode 1** (pure-function workers used by [[WorkerPool]]).
|
||||||
|
* Native platforms run JavaScript inside an embedded engine (V8 / JavaScriptCore)
|
||||||
|
* without the browser host API, and mini-game platforms forbid runtime code evaluation and have no
|
||||||
|
* `Blob` (they use `createWorker` with a packaged script path instead), so both report `false` here
|
||||||
|
* and mode 1 falls back to running synchronously on the main thread. Use [[createWorker]]`(path)`
|
||||||
|
* (mode 2) for a real worker on a mini-game platform.
|
||||||
|
*
|
||||||
|
* NOTE: this answers "can I build a worker from a FUNCTION". It says nothing about whether the
|
||||||
|
* platform has workers at all — for that use [[getWorkerConcurrencyLimit]], which is nonzero on all
|
||||||
|
* nine mini-game platforms except Taobao. Conflating the two is what made a WeChat V2 build report
|
||||||
|
* an optimal worker count of 1.
|
||||||
|
* @zh
|
||||||
|
* 检测当前环境是否支持从序列化函数创建 Web Worker
|
||||||
|
* (即 `Worker` 构造器 + `Blob` + `URL.createObjectURL` 三者齐全)。
|
||||||
|
*
|
||||||
|
* 这是**模式一**([[WorkerPool]] 使用的纯函数 Worker)所需的能力。
|
||||||
|
* 原生平台在嵌入式 JS 引擎(V8 / JavaScriptCore)中运行、没有浏览器宿主 API;小游戏平台禁止运行时代码求值
|
||||||
|
* 且没有 `Blob`(它们用 `createWorker` + 打包脚本路径),因此两者这里都返回 `false`,
|
||||||
|
* 模式一自动降级为主线程同步执行。小游戏平台上若要真正的 Worker,请用 [[createWorker]]`(path)`(模式二)。
|
||||||
|
*
|
||||||
|
* 注意:本函数回答的是"能否从**函数**构建 Worker",与平台到底有没有 Worker 无关——后者请用
|
||||||
|
* [[getWorkerConcurrencyLimit]],除淘宝外它在全部 9 个小游戏平台上都非零。
|
||||||
|
* 把两者混为一谈,正是微信 V2 构建把最优 Worker 数报成 1 的原因。
|
||||||
|
*/
|
||||||
|
export function isWorkerSupported (): boolean {
|
||||||
|
return getWorkerBackend().supportsFunctionWorker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Suggest a sensible worker count for CPU-bound (compute-heavy) tasks.
|
||||||
|
*
|
||||||
|
* The platform's concurrency cap is applied FIRST, because on seven of the nine mini-game platforms
|
||||||
|
* the limit is exactly one worker — a platform restriction, not a hardware one. Only where the
|
||||||
|
* platform allows many (Web, WeChat V2 standard worker) does the hardware estimate apply:
|
||||||
|
* `hardwareConcurrency - 1`, deliberately leaving one logical core for the main thread (rendering +
|
||||||
|
* game logic). This is a *starting point*, not a universal answer: I/O-bound tasks can benefit from
|
||||||
|
* more workers, and tiny per-frame tasks are often better off with `1`.
|
||||||
|
*
|
||||||
|
* Where `navigator.hardwareConcurrency` is unavailable — as is typically the case on mini-game
|
||||||
|
* platforms, which expose device info through their own APIs rather than `navigator` — this
|
||||||
|
* conservatively returns `1`. Size such a pool explicitly instead
|
||||||
|
* (`new WorkerPool(path, { maxWorkers: 4 })`).
|
||||||
|
*
|
||||||
|
* Returns `1` when the platform has no worker at all (native platforms, Taobao), matching the single
|
||||||
|
* inline executor the pool falls back to.
|
||||||
|
*
|
||||||
|
* @zh
|
||||||
|
* 为 CPU 密集型(重计算)任务推荐一个合理的 Worker 数量。
|
||||||
|
*
|
||||||
|
* **平台并发上限优先**,因为 9 个小游戏平台中有 7 个上限恰好是 1 个 Worker——这是平台限制而非硬件限制。
|
||||||
|
* 只有平台允许多 Worker 时(Web、微信 V2 标准 Worker)才采用硬件估算:`hardwareConcurrency - 1`,
|
||||||
|
* 刻意给主线程(渲染 + 游戏逻辑)留一个逻辑核。这是一个*起点*,不是普适答案:I/O 型任务可以开更多 Worker,
|
||||||
|
* 而每帧的小任务往往用 `1` 个更合适。
|
||||||
|
*
|
||||||
|
* 当 `navigator.hardwareConcurrency` 不可用时——**包括全部小游戏平台**(它们都不暴露 `navigator`)——
|
||||||
|
* 保守返回 `1`。这类平台请显式指定池大小(`new WorkerPool(path, { maxWorkers: 4 })`)。
|
||||||
|
*
|
||||||
|
* 平台完全不支持 Worker 时(原生平台、淘宝)返回 `1`,与池降级使用的单个内联执行器一致。
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* const pool = new WorkerPool(myPureFn, {
|
||||||
|
* maxWorkers: getOptimalWorkerCount(),
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function getOptimalWorkerCount (): number {
|
||||||
|
const limit = getWorkerBackend().concurrencyLimit;
|
||||||
|
// No worker at all: the pool can only ever run one inline executor.
|
||||||
|
if (limit === 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
// A hard platform cap (the seven single-worker mini-game platforms) wins over any hardware estimate.
|
||||||
|
// NOTE: the previous implementation reached this answer only by accident — it short-circuited on
|
||||||
|
// `isWorkerSupported()`, which tests FUNCTION-mode capability (Worker + Blob + URL). A WeChat V2
|
||||||
|
// runtime has real multi-worker support but no Blob, so it was misreported as capped at 1.
|
||||||
|
if (limit !== Infinity) {
|
||||||
|
return limit;
|
||||||
|
}
|
||||||
|
const hc = getWorkerBackend().hardwareConcurrency;
|
||||||
|
return Math.max(1, Math.floor(hc) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Whether the mini-game runtime supports the **standard (WeChat V2) worker**: multiple concurrent
|
||||||
|
* workers, `SharedArrayBuffer`, transfer lists in `postMessage`, `OffscreenCanvas`, etc.
|
||||||
|
*
|
||||||
|
* This is a WeChat-only capability today (detected via `minigame.env.isSupportStandardWorker`), but it
|
||||||
|
* is expressed as a backend capability rather than a platform check, so the answer stays correct if
|
||||||
|
* another platform later ships a standard worker.
|
||||||
|
*
|
||||||
|
* V2 is in grey release, so this MUST be checked at runtime before relying on any V2-only capability.
|
||||||
|
* It safely returns `false` (i.e. fall back to the single-worker generation) when:
|
||||||
|
* - the platform is not a mini-game platform at all (Web / native);
|
||||||
|
* - the platform has no `env.isSupportStandardWorker` (every non-WeChat mini-game platform);
|
||||||
|
* - `minigame.env` is undefined (old base library);
|
||||||
|
* - running in the WeChat devtools (V2 is not supported there yet).
|
||||||
|
*
|
||||||
|
* Without V2 the hard constraints are: at most **1** concurrent worker, data is structured-cloned
|
||||||
|
* (no transfer), and no platform API / rendering inside the worker.
|
||||||
|
* @zh
|
||||||
|
* 小游戏运行时是否支持**标准(微信 V2)Worker**:多并发 Worker、`SharedArrayBuffer`、
|
||||||
|
* `postMessage` 的 transfer 列表、`OffscreenCanvas` 等。
|
||||||
|
*
|
||||||
|
* 目前这是微信独有的能力(通过 `minigame.env.isSupportStandardWorker` 检测),但它被表达为后端能力
|
||||||
|
* 而非平台判断,因此将来若其他平台也推出标准 Worker,这里的答案依然正确。
|
||||||
|
*
|
||||||
|
* V2 仍在灰度,因此依赖任何 V2 能力前**必须**运行时检测。以下情况安全返回 `false`(即回退到单 Worker 代际):
|
||||||
|
* - 根本不是小游戏平台(Web / 原生);
|
||||||
|
* - 平台没有 `env.isSupportStandardWorker`(所有非微信小游戏平台);
|
||||||
|
* - `minigame.env` 为 undefined(旧基础库);
|
||||||
|
* - 微信开发者工具中运行(V2 暂不支持)。
|
||||||
|
*
|
||||||
|
* 无 V2 时的硬约束:最多 **1** 个并发 Worker、数据走结构化克隆(无 transfer)、Worker 内无平台 API / 渲染。
|
||||||
|
*/
|
||||||
|
export function isSupportStandardWorker (): boolean {
|
||||||
|
return getWorkerBackend().supportsStandardWorker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Result of [[checkWorkerScript]]: whether the platform worker environment is fully set up for a script path.
|
||||||
|
* @zh [[checkWorkerScript]] 的结果:平台 Worker 环境对某脚本路径是否设置完整。
|
||||||
|
*/
|
||||||
|
export interface IWorkerScriptStatus {
|
||||||
|
/**
|
||||||
|
* @en Whether a worker can be used for this path. Only when `true` should you go the worker route.
|
||||||
|
* @zh 该路径能否使用 Worker。仅当为 `true` 时才应走 Worker 路线。
|
||||||
|
*/
|
||||||
|
ready: boolean;
|
||||||
|
/**
|
||||||
|
* @en Worker version: `2` = standard (WeChat V2) worker, `1` = single-worker generation, `0` = unavailable.
|
||||||
|
* @zh Worker 版本:`2` = 标准(微信 V2)Worker,`1` = 单 Worker 代际,`0` = 不可用。
|
||||||
|
*/
|
||||||
|
version: 0 | 1 | 2;
|
||||||
|
/**
|
||||||
|
* @en Human-readable reason when not ready (empty string when ready). Suitable for error messages.
|
||||||
|
* @zh 不可用时的原因说明(可用时为空字符串),可直接用于报错信息。
|
||||||
|
*/
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Check whether the platform's worker environment is **fully set up** for the given script path.
|
||||||
|
*
|
||||||
|
* "Fully set up" means ALL of the following hold:
|
||||||
|
* 1. the platform exposes a worker API at all (`minigame.createWorker`, or a global `Worker`);
|
||||||
|
* 2. the path is valid: a non-empty **relative** path ending with `.js` (mini-game platforms reject
|
||||||
|
* absolute paths and non-JS files);
|
||||||
|
* 3. on mini-game platforms, the file **actually exists** in the code package (verified via
|
||||||
|
* `minigame.getFileSystemManager().accessSync`) and is **not empty** (best-effort `statSync`).
|
||||||
|
* A missing file usually means it was not placed in the workers directory declared in
|
||||||
|
* `game.json` (WeChat) / `manifest.json` (quick game) / `app.json`, or its subpackage has not
|
||||||
|
* been downloaded yet.
|
||||||
|
*
|
||||||
|
* When `ready` is `true`, `version` tells you which worker generation you got (`2` = WeChat standard
|
||||||
|
* multi-worker, `1` = single-worker generation). When `ready` is `false`, `reason` explains why, and
|
||||||
|
* callers should fall back to a standard Web `Worker` (if any), then to synchronous execution.
|
||||||
|
* @zh
|
||||||
|
* 检查平台的 Worker 环境对给定脚本路径是否**设置完整**。
|
||||||
|
*
|
||||||
|
* "设置完整"指以下条件全部成立:
|
||||||
|
* 1. 平台确实暴露了 Worker API(`minigame.createWorker`,或全局 `Worker`);
|
||||||
|
* 2. 路径合法:非空、**相对路径**、以 `.js` 结尾(小游戏平台会拒绝绝对路径与非 JS 文件);
|
||||||
|
* 3. 在小游戏平台上,文件**确实存在**于代码包中(通过 `minigame.getFileSystemManager().accessSync`
|
||||||
|
* 校验)且**非空**(尽力而为的 `statSync`)。文件缺失通常意味着它没被放进 `game.json`(微信)/
|
||||||
|
* `manifest.json`(快游戏)/ `app.json` 声明的 workers 目录,或所在分包尚未下载。
|
||||||
|
*
|
||||||
|
* `ready` 为 `true` 时,`version` 表明拿到的 Worker 代际(`2` = 微信标准多 Worker,`1` = 单 Worker 代际)。
|
||||||
|
* `ready` 为 `false` 时,`reason` 说明原因,调用方应降级到标准 Web `Worker`(若有),再不行就同步执行。
|
||||||
|
*/
|
||||||
|
export function checkWorkerScript (path: string): IWorkerScriptStatus {
|
||||||
|
return getWorkerBackend().diagnose(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* The maximum number of worker instances that can run **concurrently** on the current platform.
|
||||||
|
*
|
||||||
|
* - Web (global `Worker`): effectively unlimited → `Infinity`.
|
||||||
|
* - WeChat **V2** standard worker (`env.isSupportStandardWorker`): multiple workers → `Infinity`.
|
||||||
|
* - WeChat V1, ByteDance, Alipay, Baidu, and the quick-game family (Huawei / OPPO / vivo / Xiaomi):
|
||||||
|
* only ONE worker at a time → `1`.
|
||||||
|
* - Taobao mini-game and native platforms (no worker API at all) → `0`.
|
||||||
|
*
|
||||||
|
* A cap of `1` means the platform has a worker but no parallelism: [[WorkerPool]] there is an
|
||||||
|
* **asynchronous offload queue** — it frees the main thread from a long task, but it cannot run two
|
||||||
|
* tasks at once. [[WorkerPool]] in **script mode** (`new WorkerPool(path)`) already caps its pool size
|
||||||
|
* per platform automatically (via [[checkWorkerScript]]), so it never tries to create more workers
|
||||||
|
* than the platform allows — creating a second worker on a single-worker platform fails.
|
||||||
|
*
|
||||||
|
* Do NOT pass this result directly as `maxWorkers`: where it returns `Infinity` the pool treats that
|
||||||
|
* as "not specified". Pass a concrete number instead:
|
||||||
|
* ```ts
|
||||||
|
* const pool = new WorkerPool('workers/my-task/index.js', { maxWorkers: 4 });
|
||||||
|
* ```
|
||||||
|
* @zh
|
||||||
|
* 当前平台上能够**并发**运行的 worker 实例数量上限。
|
||||||
|
*
|
||||||
|
* - Web(全局 `Worker`):实际上无限制 → `Infinity`。
|
||||||
|
* - 微信 **V2** 标准 Worker(`env.isSupportStandardWorker`):支持多 Worker → `Infinity`。
|
||||||
|
* - 微信 V1、抖音、支付宝、百度,以及快游戏家族(华为 / OPPO / vivo / 小米):同一时刻仅 1 个 → `1`。
|
||||||
|
* - 淘宝小游戏与原生平台(完全没有 Worker API)→ `0`。
|
||||||
|
*
|
||||||
|
* 上限为 `1` 意味着平台有 Worker 但**没有并行能力**:此时 [[WorkerPool]] 是一个**异步卸载队列**——
|
||||||
|
* 它能把长任务从主线程挪走,但无法同时跑两个任务。[[WorkerPool]] **脚本模式**(`new WorkerPool(path)`)
|
||||||
|
* 已通过 [[checkWorkerScript]] 自动按平台封顶池大小,不会创建超过平台允许的 Worker 数——
|
||||||
|
* 在单 Worker 平台上创建第二个会失败。
|
||||||
|
*
|
||||||
|
* 不要把本函数的返回值直接传给 `maxWorkers`:返回 `Infinity` 时池会将其视为"未指定"。请传具体数值:
|
||||||
|
* ```ts
|
||||||
|
* const pool = new WorkerPool('workers/my-task/index.js', { maxWorkers: 4 });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function getWorkerConcurrencyLimit (): number {
|
||||||
|
return getWorkerBackend().concurrencyLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Create a worker from a packaged script path (**mode 2**), aligned with `minigame.createWorker`.
|
||||||
|
* - Mini-game platforms (all nine): `minigame.createWorker(path)` — the script must live in the
|
||||||
|
* packaged workers directory declared in `game.json` (WeChat) / `manifest.json` (quick game) /
|
||||||
|
* `app.json`; if it is in a subpackage, download that subpackage first.
|
||||||
|
* - Web: `new Worker(path)` (the script must be same-origin).
|
||||||
|
*
|
||||||
|
* Unlike mode 1, this works on mini-game platforms because the worker code is a real packaged file
|
||||||
|
* rather than a runtime-serialized string (which those platforms forbid). The returned [[IWorker]]
|
||||||
|
* exposes the WeChat-aligned messaging API, and the caller defines its own message protocol
|
||||||
|
* (no envelope is imposed).
|
||||||
|
*
|
||||||
|
* Platform order matters and is decided by the backend, not by a platform constant: on a mini-game
|
||||||
|
* build the mini-game worker is tried first, and only if it is not fully set up (script missing,
|
||||||
|
* subpackage not yet downloaded, base library too old) does it fall through to a global `Worker`
|
||||||
|
* (which some devtools environments provide), then to a precise error.
|
||||||
|
* @zh
|
||||||
|
* 从打包好的脚本路径创建 Worker(**模式二**),对齐 `minigame.createWorker`。
|
||||||
|
* - 小游戏平台(全部 9 个):`minigame.createWorker(path)`——脚本须位于 `game.json`(微信)/
|
||||||
|
* `manifest.json`(快游戏)/ `app.json` 声明的 workers 目录内;若在分包中,需先下载该分包。
|
||||||
|
* - Web:`new Worker(path)`(脚本需同源)。
|
||||||
|
*
|
||||||
|
* 与模式一不同,这在小游戏平台上可用,因为 Worker 代码是真实打包文件而非运行时序列化字符串
|
||||||
|
* (那些平台禁止后者)。返回的 [[IWorker]] 暴露对齐微信的消息 API,协议由调用方自定义(不强加信封)。
|
||||||
|
*
|
||||||
|
* 平台顺序很重要,且由后端而非平台常量决定:小游戏构建下优先尝试小游戏 Worker,只有当它未完全就绪时
|
||||||
|
* (脚本缺失、分包未下载、基础库过旧)才降级到全局 `Worker`(部分开发者工具环境提供),再不行就精确报错。
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
function createWorkerFromPath (path: string): IWorker {
|
||||||
|
if (typeof path !== 'string' || !path) {
|
||||||
|
throw new TypeError(getError(16515));
|
||||||
|
}
|
||||||
|
return getWorkerBackend().createScriptWorker(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en
|
||||||
|
* Create a worker. The signature is aligned with the mini-game `createWorker`:
|
||||||
|
*
|
||||||
|
* - `createWorker(path: string)` → **mode 2**: a worker loaded from a packaged script. Web uses
|
||||||
|
* `new Worker(path)`; every mini-game platform that has a worker uses
|
||||||
|
* `minigame.createWorker(path)` (WeChat / ByteDance / Alipay / Baidu / Huawei / OPPO / vivo /
|
||||||
|
* Xiaomi). Works on all of them.
|
||||||
|
* - `createWorker(fn: WorkerTask)` → **mode 1**: a worker built from a self-contained function
|
||||||
|
* (**Web only**). On mini-game platforms and native this throws, because they forbid rebuilding a
|
||||||
|
* function from source — use [[WorkerPool]] instead, which automatically falls back to
|
||||||
|
* synchronous execution there.
|
||||||
|
*
|
||||||
|
* Both return an [[IWorker]] (`postMessage` / `onMessage` / `onError` / `terminate`). Check
|
||||||
|
* [[getWorkerCapabilities]] first if you need to know whether the platform has a worker at all
|
||||||
|
* (Taobao mini-game and native do not).
|
||||||
|
* @zh
|
||||||
|
* 创建一个 Worker,签名对齐小游戏的 `createWorker`:
|
||||||
|
*
|
||||||
|
* - `createWorker(path: string)` → **模式二**:从打包脚本加载 Worker。Web 用 `new Worker(path)`;
|
||||||
|
* 每个有 Worker 的小游戏平台用 `minigame.createWorker(path)`(微信 / 抖音 / 支付宝 / 百度 / 华为 /
|
||||||
|
* OPPO / vivo / 小米),两端都可用。
|
||||||
|
* - `createWorker(fn: WorkerTask)` → **模式一**:从自包含函数构建 Worker(**仅 Web**)。
|
||||||
|
* 小游戏平台与原生下会抛错,因为它们禁止用源码重建函数——请改用 [[WorkerPool]],
|
||||||
|
* 它在这些平台会自动降级为同步执行。
|
||||||
|
*
|
||||||
|
* 两者都返回 [[IWorker]](`postMessage` / `onMessage` / `onError` / `terminate`)。若需要先知道平台
|
||||||
|
* 到底有没有 Worker(淘宝小游戏与原生没有),请先查 [[getWorkerCapabilities]]。
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* // Mode 2: your own packaged worker script (Web + all worker-capable mini-game platforms).
|
||||||
|
* const worker = cc.createWorker('workers/my-worker/index.js');
|
||||||
|
* worker.onMessage((res) => { console.log(res); });
|
||||||
|
* worker.postMessage({ cmd: 'compute', data });
|
||||||
|
* worker.terminate();
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export function createWorker (path: string): IWorker;
|
||||||
|
export function createWorker (fn: WorkerTask): IWorker;
|
||||||
|
export function createWorker (pathOrFn: string | WorkerTask): IWorker {
|
||||||
|
if (typeof pathOrFn === 'function') {
|
||||||
|
const w = getWorkerBackend().createFunctionWorker(pathOrFn);
|
||||||
|
if (!w) {
|
||||||
|
throw new Error(getError(16516));
|
||||||
|
}
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
return createWorkerFromPath(pathOrFn);
|
||||||
|
}
|
||||||
@@ -52,6 +52,7 @@ class Particle {
|
|||||||
public pos = new Vec2(0, 0);
|
public pos = new Vec2(0, 0);
|
||||||
public startPos = new Vec2(0, 0);
|
public startPos = new Vec2(0, 0);
|
||||||
public color = new Color(0, 0, 0, 255);
|
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 deltaColor = { r: 0, g: 0, b: 0, a: 255 };
|
||||||
public size = 0;
|
public size = 0;
|
||||||
public deltaSize = 0;
|
public deltaSize = 0;
|
||||||
@@ -81,6 +82,8 @@ const pool = new ParticlePool((par: Particle): void => {
|
|||||||
par.pos.set(Vec2.ZERO);
|
par.pos.set(Vec2.ZERO);
|
||||||
par.startPos.set(Vec2.ZERO);
|
par.startPos.set(Vec2.ZERO);
|
||||||
par.color.set(0, 0, 0, 255);
|
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.r = par.deltaColor.g = par.deltaColor.b = 0;
|
||||||
par.deltaColor.a = 255;
|
par.deltaColor.a = 255;
|
||||||
par.size = 0;
|
par.size = 0;
|
||||||
@@ -111,6 +114,7 @@ export class Simulator {
|
|||||||
private elapsed = 0;
|
private elapsed = 0;
|
||||||
private emitCounter = 0;
|
private emitCounter = 0;
|
||||||
private _worldRotation = 0;
|
private _worldRotation = 0;
|
||||||
|
private _parentAlpha = 0.0;
|
||||||
private declare sys: ParticleSystem2D;
|
private declare sys: ParticleSystem2D;
|
||||||
|
|
||||||
constructor (system) {
|
constructor (system) {
|
||||||
@@ -169,10 +173,10 @@ export class Simulator {
|
|||||||
const endColor = psys.endColor;
|
const endColor = psys.endColor;
|
||||||
const endColorVar = psys.endColorVar;
|
const endColorVar = psys.endColorVar;
|
||||||
|
|
||||||
particle.color.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
|
particle.curColor.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.curColor.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.curColor.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.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.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.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;
|
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);
|
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 {
|
public step (dt: number): void {
|
||||||
const assembler = this.sys.assembler as Particle2DAssembler;
|
const assembler = this.sys.assembler as Particle2DAssembler;
|
||||||
const psys = this.sys;
|
const psys = this.sys;
|
||||||
@@ -379,6 +391,8 @@ export class Simulator {
|
|||||||
this.updateUVs();
|
this.updateUVs();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this._updateColor();
|
||||||
|
|
||||||
// Used to reduce memory allocation / creation within the loop
|
// Used to reduce memory allocation / creation within the loop
|
||||||
let particleIdx = 0;
|
let particleIdx = 0;
|
||||||
while (particleIdx < particles.length) {
|
while (particleIdx < particles.length) {
|
||||||
@@ -431,10 +445,15 @@ export class Simulator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// color
|
// color
|
||||||
particle.color.r += particle.deltaColor.r * dt;
|
particle.curColor.r += particle.deltaColor.r * dt;
|
||||||
particle.color.g += particle.deltaColor.g * dt;
|
particle.curColor.g += particle.deltaColor.g * dt;
|
||||||
particle.color.b += particle.deltaColor.b * dt;
|
particle.curColor.b += particle.deltaColor.b * dt;
|
||||||
particle.color.a += particle.deltaColor.a * 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
|
// size
|
||||||
particle.size += particle.deltaSize * dt;
|
particle.size += particle.deltaSize * dt;
|
||||||
|
|||||||
@@ -797,7 +797,7 @@ export class ParticleSystem2D extends UIRenderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _startPreview (): void {
|
private _startPreview (): void {
|
||||||
if (this._preview) {
|
if (!this._preview) {
|
||||||
this.resetSystem();
|
this.resetSystem();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { ccclass, type, serializable, editable, range } from 'cc.decorator';
|
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 CurveRange from './animator/curve-range';
|
||||||
import type { ParticleSystem } from './particle-system';
|
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;
|
let preFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration) - dt;
|
||||||
preFrameTime = (preFrameTime > 0.0) ? preFrameTime : 0.0;
|
preFrameTime = (preFrameTime > 0.0) ? preFrameTime : 0.0;
|
||||||
const curFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration);
|
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));
|
psys.emit(this.count.evaluate(this._curTime / psys.duration, 1), dt - (curFrameTime - this._curTime));
|
||||||
this._curTime += this.repeatInterval;
|
this._curTime += this.repeatInterval;
|
||||||
--this._remainingCount;
|
--this._remainingCount;
|
||||||
|
|||||||
+10
-1
@@ -25,7 +25,7 @@
|
|||||||
import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable,
|
import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable,
|
||||||
range, visible, override, displayName } from 'cc.decorator';
|
range, visible, override, displayName } from 'cc.decorator';
|
||||||
import { Material, Texture2D } from '../asset/assets';
|
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 { LineModel } from './models/line-model';
|
||||||
import { builtinResMgr } from '../asset/asset-manager';
|
import { builtinResMgr } from '../asset/asset-manager';
|
||||||
import CurveRange from './animator/curve-range';
|
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 {
|
protected _onMaterialModified (index: number, material: Material | null): void {
|
||||||
super._onMaterialModified(index, material);
|
super._onMaterialModified(index, material);
|
||||||
const matIns = this.getMaterialInstance(0);
|
const matIns = this.getMaterialInstance(0);
|
||||||
|
|||||||
+14
-4
@@ -29,7 +29,8 @@ import { Vec2, Vec3 } from '../core/math';
|
|||||||
* @zh 此类生成噪声纹理。
|
* @zh 此类生成噪声纹理。
|
||||||
*/
|
*/
|
||||||
export class ParticleNoise {
|
export class ParticleNoise {
|
||||||
private permutation: number[] = [151, 160, 137, 91, 90, 15,
|
private static readonly DEFAULT_PERMUTATION: readonly number[] = [
|
||||||
|
151, 160, 137, 91, 90, 15,
|
||||||
131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
|
131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
|
||||||
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
|
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
|
||||||
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,
|
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,
|
||||||
@@ -44,9 +45,19 @@ export class ParticleNoise {
|
|||||||
138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
|
138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
private static build512 (src: readonly number[] | number[]): Uint8Array {
|
||||||
|
const p = new Uint8Array(512);
|
||||||
|
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = src[i]; }
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
private permutation: number[] = ParticleNoise.DEFAULT_PERMUTATION as number[];
|
||||||
|
private permutation512: Uint8Array = ParticleNoise.build512(ParticleNoise.DEFAULT_PERMUTATION);
|
||||||
|
|
||||||
constructor (permutation?: number[]) {
|
constructor (permutation?: number[]) {
|
||||||
if (permutation) {
|
if (permutation) {
|
||||||
this.permutation = permutation;
|
this.permutation = permutation.slice();
|
||||||
|
this.permutation512 = ParticleNoise.build512(this.permutation);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,8 +72,7 @@ export class ParticleNoise {
|
|||||||
* @returns @en Texture pixel generated. @zh 返回生成的噪声纹理值。
|
* @returns @en Texture pixel generated. @zh 返回生成的噪声纹理值。
|
||||||
*/
|
*/
|
||||||
public noise (x: number, y: number, z: number, min = 0, max = 1): number {
|
public noise (x: number, y: number, z: number, min = 0, max = 1): number {
|
||||||
const p: number[] = new Array(512);
|
const p: Uint8Array = this.permutation512;
|
||||||
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = this.permutation[i]; }
|
|
||||||
|
|
||||||
const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT
|
const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT
|
||||||
const Y = Math.floor(y) & 255; // CONTAINS POINT.
|
const Y = Math.floor(y) & 255; // CONTAINS POINT.
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ import VelocityOvertimeModule from './animator/velocity-overtime';
|
|||||||
import Burst from './burst';
|
import Burst from './burst';
|
||||||
import ShapeModule from './emitter/shape-module';
|
import ShapeModule from './emitter/shape-module';
|
||||||
import { ParticleCullingMode, ParticleSpace } from './enum';
|
import { ParticleCullingMode, ParticleSpace } from './enum';
|
||||||
import { particleEmitZAxis } from './particle-general-function';
|
import { isCurveTwoValues, particleEmitZAxis } from './particle-general-function';
|
||||||
import ParticleSystemRenderer from './renderer/particle-system-renderer-data';
|
import ParticleSystemRenderer from './renderer/particle-system-renderer-data';
|
||||||
import TrailModule from './renderer/trail';
|
import TrailModule from './renderer/trail';
|
||||||
import { ParticleSystemRendererBase } from './renderer/particle-system-renderer-base';
|
import { ParticleSystemRendererBase } from './renderer/particle-system-renderer-base';
|
||||||
@@ -141,7 +141,7 @@ export class ParticleSystem extends ModelRenderer {
|
|||||||
@range([0, Number.POSITIVE_INFINITY])
|
@range([0, Number.POSITIVE_INFINITY])
|
||||||
@displayOrder(10)
|
@displayOrder(10)
|
||||||
@tooltip('i18n:particle_system.startSizeY')
|
@tooltip('i18n:particle_system.startSizeY')
|
||||||
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
|
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
|
||||||
public startSizeY = new CurveRange();
|
public startSizeY = new CurveRange();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -153,7 +153,7 @@ export class ParticleSystem extends ModelRenderer {
|
|||||||
@range([0, Number.POSITIVE_INFINITY])
|
@range([0, Number.POSITIVE_INFINITY])
|
||||||
@displayOrder(10)
|
@displayOrder(10)
|
||||||
@tooltip('i18n:particle_system.startSizeZ')
|
@tooltip('i18n:particle_system.startSizeZ')
|
||||||
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
|
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
|
||||||
public startSizeZ = new CurveRange();
|
public startSizeZ = new CurveRange();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -184,7 +184,7 @@ export class ParticleSystem extends ModelRenderer {
|
|||||||
@radian
|
@radian
|
||||||
@displayOrder(12)
|
@displayOrder(12)
|
||||||
@tooltip('i18n:particle_system.startRotationX')
|
@tooltip('i18n:particle_system.startRotationX')
|
||||||
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
|
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
|
||||||
public startRotationX = new CurveRange();
|
public startRotationX = new CurveRange();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -196,7 +196,7 @@ export class ParticleSystem extends ModelRenderer {
|
|||||||
@radian
|
@radian
|
||||||
@displayOrder(12)
|
@displayOrder(12)
|
||||||
@tooltip('i18n:particle_system.startRotationY')
|
@tooltip('i18n:particle_system.startRotationY')
|
||||||
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
|
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
|
||||||
public startRotationY = new CurveRange();
|
public startRotationY = new CurveRange();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -233,8 +233,8 @@ export class ParticleSystem extends ModelRenderer {
|
|||||||
public startLifetime = new CurveRange();
|
public startLifetime = new CurveRange();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en Particle system duration time.
|
* @en Particle system emitter duration time.
|
||||||
* @zh 粒子系统运行时间。
|
* @zh 粒子系统发射器运行时间。
|
||||||
*/
|
*/
|
||||||
@serializable
|
@serializable
|
||||||
@displayOrder(0)
|
@displayOrder(0)
|
||||||
@@ -1455,16 +1455,18 @@ export class ParticleSystem extends ModelRenderer {
|
|||||||
|
|
||||||
if (!self._isEmitting) return;
|
if (!self._isEmitting) return;
|
||||||
|
|
||||||
|
const randTime = isCurveTwoValues(self.rateOverTime) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
|
||||||
// emit by rateOverTime
|
// emit by rateOverTime
|
||||||
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, 1)! * dt;
|
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, randTime)! * dt;
|
||||||
if (self._emitRateTimeCounter > 1) {
|
if (self._emitRateTimeCounter > 1) {
|
||||||
const emitNum = Math.floor(self._emitRateTimeCounter);
|
const emitNum = Math.floor(self._emitRateTimeCounter);
|
||||||
self._emitRateTimeCounter -= emitNum;
|
self._emitRateTimeCounter -= emitNum;
|
||||||
self.emit(emitNum, dt);
|
self.emit(emitNum, dt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const randDist = isCurveTwoValues(self.rateOverDistance) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
|
||||||
// emit by rateOverDistance
|
// emit by rateOverDistance
|
||||||
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, 1)!;
|
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, randDist)!;
|
||||||
if (rateOverDistance > 0) {
|
if (rateOverDistance > 0) {
|
||||||
Vec3.copy(self._oldWPos, self._curWPos);
|
Vec3.copy(self._oldWPos, self._curWPos);
|
||||||
self.node.getWorldPosition(self._curWPos);
|
self.node.getWorldPosition(self._curWPos);
|
||||||
|
|||||||
@@ -747,6 +747,12 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
|||||||
this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable;
|
this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable;
|
||||||
this._defines[INSTANCE_PARTICLE] = this._useInstance;
|
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);
|
mat.recompileShaders(this._defines);
|
||||||
if (this._model) {
|
if (this._model) {
|
||||||
this._model.updateMaterial(mat);
|
this._model.updateMaterial(mat);
|
||||||
@@ -776,6 +782,13 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
|||||||
_matInsInfo.subModelIdx = 0;
|
_matInsInfo.subModelIdx = 0;
|
||||||
}
|
}
|
||||||
mat = mat || this._defaultTrailMat!;
|
mat = mat || this._defaultTrailMat!;
|
||||||
|
|
||||||
|
const matIns: MaterialInstance | null = ps.getMaterialInstance(1);
|
||||||
|
if (matIns === null || matIns === undefined) {
|
||||||
|
ps.setSharedMaterial(mat.parent, 1); // set material[1] as trail material for ui-mesh-renderer to use
|
||||||
|
ps.setMaterialInstance(mat, 1);
|
||||||
|
}
|
||||||
|
|
||||||
const texture = mat.getProperty('mainTexture', 0) as Texture2D | null;
|
const texture = mat.getProperty('mainTexture', 0) as Texture2D | null;
|
||||||
if (texture && texture.isAlphaAtlas) {
|
if (texture && texture.isAlphaAtlas) {
|
||||||
this._trailDefines[CC_USE_EMBEDDED_ALPHA] = true;
|
this._trailDefines[CC_USE_EMBEDDED_ALPHA] = true;
|
||||||
|
|||||||
@@ -377,7 +377,10 @@ export default class TrailModule {
|
|||||||
if (this.lifeTime.getMax() < 1.0) {
|
if (this.lifeTime.getMax() < 1.0) {
|
||||||
warnID(6036);
|
warnID(6036);
|
||||||
}
|
}
|
||||||
this._trailNum = Math.ceil(psTime * Math.ceil(this.lifeTime.getMax()) * 60 * (psRate * duration + burstCount));
|
let pCount: number = psRate * duration; // potential particle count
|
||||||
|
pCount = ps.prewarm ? pCount * 2 : pCount; // if prewarm we need double space
|
||||||
|
pCount = pCount > ps.capacity ? ps.capacity : pCount; // max particle count is less/equal than capacity
|
||||||
|
this._trailNum = Math.ceil(psTime * Math.ceil(this.lifeTime.getMax()) * 60 * (pCount + burstCount));
|
||||||
this._trailSegments = new Pool(
|
this._trailSegments = new Pool(
|
||||||
(): TrailSegment => new TrailSegment(10),
|
(): TrailSegment => new TrailSegment(10),
|
||||||
Math.ceil(psRate * duration),
|
Math.ceil(psRate * duration),
|
||||||
|
|||||||
@@ -141,7 +141,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
|||||||
|
|
||||||
if (!v) {
|
if (!v) {
|
||||||
if (this._debugGraphics) {
|
if (this._debugGraphics) {
|
||||||
this._debugGraphics.node.parent = null;
|
this._debugGraphics.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ export class b2CircleShape extends b2Shape2D implements ICircleShape {
|
|||||||
|
|
||||||
_worldPosition = new Vec2();
|
_worldPosition = new Vec2();
|
||||||
get worldPosition (): Vec2 {
|
get worldPosition (): Vec2 {
|
||||||
const p = (this._shapes[0] as b2jsb.CircleShape).m_p;
|
const comp = this.collider as CircleCollider2D;
|
||||||
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
|
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
|
||||||
}
|
}
|
||||||
|
|
||||||
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
|
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import { instantiateWasm, ensureWasmModuleReady } from 'pal/wasm';
|
|||||||
import { BUILD, LOAD_BOX2D_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
import { BUILD, LOAD_BOX2D_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||||
|
|
||||||
import { game } from '../../game';
|
import { game } from '../../game';
|
||||||
import { error, sys, IVec2Like, log } from '../../core';
|
import { error, sys, IVec2Like, log, debug } from '../../core';
|
||||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||||
|
|
||||||
// eslint-disable-next-line import/no-mutable-exports
|
// eslint-disable-next-line import/no-mutable-exports
|
||||||
@@ -148,7 +148,7 @@ function initWasm (wasmFactory, wasmUrl: string): Promise<void> {
|
|||||||
}).catch((err) => reject(errorMessage(err)));
|
}).catch((err) => reject(errorMessage(err)));
|
||||||
},
|
},
|
||||||
}).then((Instance: any) => {
|
}).then((Instance: any) => {
|
||||||
log('[box2d]:box2d wasm lib loaded.');
|
debug('[box2d]:box2d wasm lib loaded.');
|
||||||
B2 = Instance;
|
B2 = Instance;
|
||||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||||
});
|
});
|
||||||
@@ -158,7 +158,7 @@ function initAsm (asmFactory): Promise<void> {
|
|||||||
return new Promise<void>((resolve, reject) => {
|
return new Promise<void>((resolve, reject) => {
|
||||||
const errorMessage = (err: any): string => `[box2d]: box2d asm lib load failed: ${err}`;
|
const errorMessage = (err: any): string => `[box2d]: box2d asm lib load failed: ${err}`;
|
||||||
asmFactory().then((instance: any) => {
|
asmFactory().then((instance: any) => {
|
||||||
log('[box2d]:box2d asm lib loaded.');
|
debug('[box2d]:box2d asm lib loaded.');
|
||||||
B2 = instance;
|
B2 = instance;
|
||||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
|||||||
|
|
||||||
if (!v) {
|
if (!v) {
|
||||||
if (this._debugGraphics) {
|
if (this._debugGraphics) {
|
||||||
this._debugGraphics.node.parent = null;
|
this._debugGraphics.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ export class B2CircleShape extends B2Shape2D implements ICircleShape {
|
|||||||
|
|
||||||
_worldPosition = new Vec2();
|
_worldPosition = new Vec2();
|
||||||
get worldPosition (): Vec2 {
|
get worldPosition (): Vec2 {
|
||||||
const p = B2.CircleShapeGetPosition(this._shapes[0]) as B2.Vec2;
|
const comp = this.collider as CircleCollider2D;
|
||||||
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
|
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
|
||||||
}
|
}
|
||||||
|
|
||||||
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): number[] { //B2.CircleShape[]
|
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): number[] { //B2.CircleShape[]
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
|||||||
|
|
||||||
if (!v) {
|
if (!v) {
|
||||||
if (this._debugGraphics) {
|
if (this._debugGraphics) {
|
||||||
this._debugGraphics.node.parent = null;
|
this._debugGraphics.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ export class b2CircleShape extends b2Shape2D implements ICircleShape {
|
|||||||
|
|
||||||
_worldPosition = new Vec2();
|
_worldPosition = new Vec2();
|
||||||
get worldPosition (): Vec2 {
|
get worldPosition (): Vec2 {
|
||||||
const p = (this._shapes[0] as b2.CircleShape).m_p;
|
const comp = this.collider as CircleCollider2D;
|
||||||
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
|
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
|
||||||
}
|
}
|
||||||
|
|
||||||
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
|
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ import { EDITOR, DEBUG, TEST, EDITOR_NOT_IN_PREVIEW } from 'internal:constants';
|
|||||||
import { IRigidBody2D } from '../spec/i-rigid-body';
|
import { IRigidBody2D } from '../spec/i-rigid-body';
|
||||||
import { IBoxShape, ICircleShape, IPolygonShape, IBaseShape } from '../spec/i-physics-shape';
|
import { IBoxShape, ICircleShape, IPolygonShape, IBaseShape } from '../spec/i-physics-shape';
|
||||||
import { IPhysicsWorld } from '../spec/i-physics-world';
|
import { IPhysicsWorld } from '../spec/i-physics-world';
|
||||||
import { errorID, log } from '../../core';
|
import { debug, errorID, log } from '../../core';
|
||||||
import { ECollider2DType, EJoint2DType } from './physics-types';
|
import { ECollider2DType, EJoint2DType } from './physics-types';
|
||||||
import { IJoint2D, IDistanceJoint, ISpringJoint, IFixedJoint, IMouseJoint,
|
import { IJoint2D, IDistanceJoint, ISpringJoint, IFixedJoint, IMouseJoint,
|
||||||
IRelativeJoint, ISliderJoint, IWheelJoint, IHingeJoint } from '../spec/i-physics-joint';
|
IRelativeJoint, ISliderJoint, IWheelJoint, IHingeJoint } from '../spec/i-physics-joint';
|
||||||
@@ -110,7 +110,7 @@ export interface IPhysicsSelector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
||||||
if (!EDITOR && !TEST) log(`[PHYSICS2D]: register ${id}.`);
|
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: register ${id}.`);
|
||||||
selector.backend[id] = wrapper;
|
selector.backend[id] = wrapper;
|
||||||
if (!selector.physicsWorld || selector.id === id) {
|
if (!selector.physicsWorld || selector.id === id) {
|
||||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||||
@@ -124,12 +124,12 @@ function switchTo (id: IPhysicsEngineId): void {
|
|||||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||||
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
||||||
//selector.physicsWorld.destroy();//todo
|
//selector.physicsWorld.destroy();//todo
|
||||||
if (!TEST) log(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
|
if (!TEST) debug(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
|
||||||
mutableSelector.id = id;
|
mutableSelector.id = id;
|
||||||
mutableSelector.wrapper = selector.backend[id];
|
mutableSelector.wrapper = selector.backend[id];
|
||||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||||
} else {
|
} else {
|
||||||
if (!EDITOR && !TEST) log(`[PHYSICS2D]: using ${mutableSelector.id}.`);
|
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: using ${mutableSelector.id}.`);
|
||||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
|
||||||
import { BUILD, LOAD_BULLET_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
import { BUILD, LOAD_BULLET_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
|
||||||
import { game } from '../../game';
|
import { game } from '../../game';
|
||||||
import { error, log, sys } from '../../core';
|
import { debug, error, sys } from '../../core';
|
||||||
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
|
||||||
import type { BulletCache } from './bullet-cache';
|
import type { BulletCache } from './bullet-cache';
|
||||||
|
|
||||||
@@ -106,7 +106,7 @@ function initWASM (wasmFactory, wasmUrl: string): Promise<void> {
|
|||||||
}).catch((err) => reject(errorMessage(err)));
|
}).catch((err) => reject(errorMessage(err)));
|
||||||
},
|
},
|
||||||
}).then((instance: any) => {
|
}).then((instance: any) => {
|
||||||
log('[bullet]:bullet wasm lib loaded.');
|
debug('[bullet]:bullet wasm lib loaded.');
|
||||||
bt = instance as Bullet.instance;
|
bt = instance as Bullet.instance;
|
||||||
globalThis.Bullet = bt as any;
|
globalThis.Bullet = bt as any;
|
||||||
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
|
||||||
@@ -117,7 +117,7 @@ function initASM (asmFactory): Promise<void> {
|
|||||||
if (asmFactory != null) {
|
if (asmFactory != null) {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||||
return asmFactory().then((instance: any) => {
|
return asmFactory().then((instance: any) => {
|
||||||
log('[bullet]:bullet asm lib loaded.');
|
debug('[bullet]:bullet asm lib loaded.');
|
||||||
bt = instance as Bullet.instance;
|
bt = instance as Bullet.instance;
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ import {
|
|||||||
import { IPhysicsWorld } from '../spec/i-physics-world';
|
import { IPhysicsWorld } from '../spec/i-physics-world';
|
||||||
import { IRigidBody } from '../spec/i-rigid-body';
|
import { IRigidBody } from '../spec/i-rigid-body';
|
||||||
import { IBoxCharacterController, ICapsuleCharacterController } from '../spec/i-character-controller';
|
import { IBoxCharacterController, ICapsuleCharacterController } from '../spec/i-character-controller';
|
||||||
import { errorID, IVec3Like, warn, cclegacy, log } from '../../core';
|
import { errorID, IVec3Like, warn, cclegacy, debug } from '../../core';
|
||||||
import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum';
|
import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum';
|
||||||
import { PhysicsMaterial } from '.';
|
import { PhysicsMaterial } from '.';
|
||||||
|
|
||||||
@@ -125,7 +125,7 @@ function updateLegacyMacro (id: string): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
|
||||||
if (!EDITOR && !TEST) log(`[PHYSICS]: register ${id}.`);
|
if (!EDITOR && !TEST) debug(`[PHYSICS]: register ${id}.`);
|
||||||
selector.backend[id] = wrapper;
|
selector.backend[id] = wrapper;
|
||||||
if (!selector.physicsWorld || selector.id === id) {
|
if (!selector.physicsWorld || selector.id === id) {
|
||||||
updateLegacyMacro(id);
|
updateLegacyMacro(id);
|
||||||
@@ -147,13 +147,13 @@ function switchTo (id: IPhysicsEngineId): void {
|
|||||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||||
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
|
||||||
selector.physicsWorld.destroy();
|
selector.physicsWorld.destroy();
|
||||||
if (!TEST) log(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
|
if (!TEST) debug(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
|
||||||
updateLegacyMacro(id);
|
updateLegacyMacro(id);
|
||||||
mutableSelector.id = id;
|
mutableSelector.id = id;
|
||||||
mutableSelector.wrapper = selector.backend[id];
|
mutableSelector.wrapper = selector.backend[id];
|
||||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||||
} else {
|
} else {
|
||||||
if (!EDITOR && !TEST) log(`[PHYSICS]: using ${id}.`);
|
if (!EDITOR && !TEST) debug(`[PHYSICS]: using ${id}.`);
|
||||||
mutableSelector.physicsWorld = createPhysicsWorld();
|
mutableSelector.physicsWorld = createPhysicsWorld();
|
||||||
}
|
}
|
||||||
if (worldInitData) {
|
if (worldInitData) {
|
||||||
@@ -185,7 +185,7 @@ export function constructDefaultWorld (data: IWorldInitData): void {
|
|||||||
if (!worldInitData) worldInitData = data;
|
if (!worldInitData) worldInitData = data;
|
||||||
if (!selector.runInEditor) return;
|
if (!selector.runInEditor) return;
|
||||||
if (!selector.physicsWorld) {
|
if (!selector.physicsWorld) {
|
||||||
if (!TEST) log(`[PHYSICS]: using ${selector.id}.`);
|
if (!TEST) debug(`[PHYSICS]: using ${selector.id}.`);
|
||||||
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
const mutableSelector = selector as Mutable<IPhysicsSelector>;
|
||||||
const world = mutableSelector.physicsWorld = createPhysicsWorld();
|
const world = mutableSelector.physicsWorld = createPhysicsWorld();
|
||||||
world.setGravity(worldInitData.gravity);
|
world.setGravity(worldInitData.gravity);
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ interface IProfilerState {
|
|||||||
frame: ICounterOption;
|
frame: ICounterOption;
|
||||||
fps: ICounterOption;
|
fps: ICounterOption;
|
||||||
draws: ICounterOption;
|
draws: ICounterOption;
|
||||||
|
dispatches: ICounterOption;
|
||||||
instances: ICounterOption;
|
instances: ICounterOption;
|
||||||
tricount: ICounterOption;
|
tricount: ICounterOption;
|
||||||
logic: ICounterOption;
|
logic: ICounterOption;
|
||||||
@@ -73,6 +74,7 @@ interface IProfilerState {
|
|||||||
const _profileInfo = {
|
const _profileInfo = {
|
||||||
fps: { desc: `Framerate (FPS)`, below: 30, average: _average, isInteger: true },
|
fps: { desc: `Framerate (FPS)`, below: 30, average: _average, isInteger: true },
|
||||||
draws: { desc: 'Draw call', isInteger: true },
|
draws: { desc: 'Draw call', isInteger: true },
|
||||||
|
dispatches: { desc: 'Dispatch call', isInteger: true },
|
||||||
frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: _average },
|
frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: _average },
|
||||||
instances: { desc: 'Instance Count', isInteger: true },
|
instances: { desc: 'Instance Count', isInteger: true },
|
||||||
tricount: { desc: 'Triangle', isInteger: true },
|
tricount: { desc: 'Triangle', isInteger: true },
|
||||||
@@ -586,6 +588,8 @@ export class Profiler extends System {
|
|||||||
|
|
||||||
const device = this._device!;
|
const device = this._device!;
|
||||||
(profilerStats.draws.counter as PerfCounter).value = device.numDrawCalls;
|
(profilerStats.draws.counter as PerfCounter).value = device.numDrawCalls;
|
||||||
|
// Native (JSB) devices expose no dispatch stats yet; WebGPU does. Treat missing as 0.
|
||||||
|
(profilerStats.dispatches.counter as PerfCounter).value = device.numDispatches ?? 0;
|
||||||
(profilerStats.instances.counter as PerfCounter).value = device.numInstances;
|
(profilerStats.instances.counter as PerfCounter).value = device.numInstances;
|
||||||
(profilerStats.bufferMemory.counter as PerfCounter).value = device.memoryStatus.bufferSize / (1024 * 1024);
|
(profilerStats.bufferMemory.counter as PerfCounter).value = device.memoryStatus.bufferSize / (1024 * 1024);
|
||||||
(profilerStats.textureMemory.counter as PerfCounter).value = device.memoryStatus.textureSize / (1024 * 1024);
|
(profilerStats.textureMemory.counter as PerfCounter).value = device.memoryStatus.textureSize / (1024 * 1024);
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ import { murmurhash2_32_gc, errorID, assertID, cclegacy, warnID } from '../../co
|
|||||||
import {
|
import {
|
||||||
BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color,
|
BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color,
|
||||||
BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet,
|
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';
|
} from '../../gfx';
|
||||||
import { EffectAsset } from '../../asset/assets/effect-asset';
|
import { EffectAsset } from '../../asset/assets/effect-asset';
|
||||||
import { IProgramInfo, programLib } from './program-lib';
|
import { IProgramInfo, programLib } from './program-lib';
|
||||||
@@ -139,6 +139,28 @@ export class Pass {
|
|||||||
if (bsInfo.isA2C !== undefined) { bs.isA2C = bsInfo.isA2C; }
|
if (bsInfo.isA2C !== undefined) { bs.isA2C = bsInfo.isA2C; }
|
||||||
if (bsInfo.isIndepend !== undefined) { bs.isIndepend = bsInfo.isIndepend; }
|
if (bsInfo.isIndepend !== undefined) { bs.isIndepend = bsInfo.isIndepend; }
|
||||||
if (bsInfo.blendColor !== undefined) { bs.blendColor = bsInfo.blendColor as Color; }
|
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._rs.assign(info.rasterizerState as RasterizerState);
|
||||||
pass._dss.assign(info.depthStencilState as DepthStencilState);
|
pass._dss.assign(info.depthStencilState as DepthStencilState);
|
||||||
|
|||||||
@@ -21,12 +21,14 @@
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
*/
|
*/
|
||||||
|
import { DEBUG } from 'internal:constants';
|
||||||
import { screenAdapter } from 'pal/screen-adapter';
|
import { screenAdapter } from 'pal/screen-adapter';
|
||||||
import { Orientation } from '../../../pal/screen-adapter/enum-type';
|
import { Orientation } from '../../../pal/screen-adapter/enum-type';
|
||||||
import {
|
import {
|
||||||
TextureType, TextureUsageBit, Format, RenderPass, Texture, Framebuffer,
|
TextureType, TextureUsageBit, Format, RenderPass, Texture, Framebuffer,
|
||||||
RenderPassInfo, Device, TextureInfo, FramebufferInfo, Swapchain, SurfaceTransform, TextureFlagBit, TextureFlags,
|
RenderPassInfo, Device, TextureInfo, FramebufferInfo, Swapchain, SurfaceTransform, TextureFlagBit, TextureFlags,
|
||||||
} from '../../gfx';
|
} from '../../gfx';
|
||||||
|
import { warn } from '../../core/platform/debug';
|
||||||
import { Root } from '../../root';
|
import { Root } from '../../root';
|
||||||
import { Camera } from '../scene';
|
import { Camera } from '../scene';
|
||||||
|
|
||||||
@@ -41,7 +43,10 @@ export interface IRenderWindowInfo {
|
|||||||
externalFlag?: TextureFlags; // external texture type normal or oes
|
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.PORTRAIT]: SurfaceTransform.IDENTITY,
|
||||||
[Orientation.LANDSCAPE_RIGHT]: SurfaceTransform.ROTATE_90,
|
[Orientation.LANDSCAPE_RIGHT]: SurfaceTransform.ROTATE_90,
|
||||||
[Orientation.PORTRAIT_UPSIDE_DOWN]: SurfaceTransform.ROTATE_180,
|
[Orientation.PORTRAIT_UPSIDE_DOWN]: SurfaceTransform.ROTATE_180,
|
||||||
@@ -253,7 +258,11 @@ export class RenderWindow {
|
|||||||
*/
|
*/
|
||||||
public resize (width: number, height: number): void {
|
public resize (width: number, height: number): void {
|
||||||
if (this._swapchain) {
|
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._width = this._swapchain.width;
|
||||||
this._height = this._swapchain.height;
|
this._height = this._swapchain.height;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -91,6 +91,9 @@ export class PointLight extends Light {
|
|||||||
* @en The luminance of the light source in LDR mode.
|
* @en The luminance of the light source in LDR mode.
|
||||||
* @zh LDR 模式下光源的亮度。
|
* @zh LDR 模式下光源的亮度。
|
||||||
*/
|
*/
|
||||||
|
get luminanceLDR (): number {
|
||||||
|
return this._luminanceLDR;
|
||||||
|
}
|
||||||
set luminanceLDR (value: number) {
|
set luminanceLDR (value: number) {
|
||||||
this._luminanceLDR = value;
|
this._luminanceLDR = value;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,11 +67,13 @@ export class ReflectionProbe {
|
|||||||
protected readonly _size = v3(1, 1, 1);
|
protected readonly _size = v3(1, 1, 1);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en Render cubemap's camera
|
* @en Camera used for probe rendering (cubemap capture or planar reflection).
|
||||||
* @zh 渲染cubemap的相机
|
* @zh 用于探针渲染的相机(cubemap 采集或平面反射)
|
||||||
*/
|
*/
|
||||||
private _camera: Camera | null = null;
|
private _camera: Camera | null = null;
|
||||||
|
|
||||||
|
private _previewCamera: Camera | null = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @en Unique id of probe.
|
* @en Unique id of probe.
|
||||||
* @zh probe的唯一id
|
* @zh probe的唯一id
|
||||||
@@ -184,6 +186,9 @@ export class ReflectionProbe {
|
|||||||
set visibility (val) {
|
set visibility (val) {
|
||||||
this._visibility = val;
|
this._visibility = val;
|
||||||
this._camera!.visibility = this._visibility;
|
this._camera!.visibility = this._visibility;
|
||||||
|
if (this._previewCamera) {
|
||||||
|
this._previewCamera.visibility = this._visibility;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -320,6 +325,21 @@ export class ReflectionProbe {
|
|||||||
this._needRender = true;
|
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 {
|
public switchProbeType (type: ProbeType, sourceCamera: Camera | null): void {
|
||||||
if (type === ProbeType.CUBE) {
|
if (type === ProbeType.CUBE) {
|
||||||
this._needRender = false;
|
this._needRender = false;
|
||||||
@@ -357,6 +377,12 @@ export class ReflectionProbe {
|
|||||||
this._camera.destroy();
|
this._camera.destroy();
|
||||||
this._camera = null;
|
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++) {
|
for (let i = 0; i < this.bakedCubeTextures.length; i++) {
|
||||||
this.bakedCubeTextures[i].destroy();
|
this.bakedCubeTextures[i].destroy();
|
||||||
}
|
}
|
||||||
@@ -410,48 +436,54 @@ export class ReflectionProbe {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _syncCameraParams (camera: Camera): void {
|
private _syncCameraParams (camera: Camera, targetCamera: Camera = this.camera): void {
|
||||||
this.camera.projectionType = camera.projectionType;
|
targetCamera.projectionType = camera.projectionType;
|
||||||
this.camera.orthoHeight = camera.orthoHeight;
|
targetCamera.orthoHeight = camera.orthoHeight;
|
||||||
this.camera.nearClip = camera.nearClip;
|
targetCamera.nearClip = camera.nearClip;
|
||||||
this.camera.farClip = camera.farClip;
|
targetCamera.farClip = camera.farClip;
|
||||||
this.camera.fov = camera.fov;
|
targetCamera.fov = camera.fov;
|
||||||
this.camera.clearFlag = camera.clearFlag;
|
targetCamera.clearFlag = camera.clearFlag;
|
||||||
this.camera.clearColor = camera.clearColor;
|
targetCamera.clearColor = camera.clearColor;
|
||||||
this.camera.priority = camera.priority - 1;
|
targetCamera.priority = camera.priority - 1;
|
||||||
this.camera.resize(camera.width, camera.height);
|
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;
|
const root = cclegacy.director.root;
|
||||||
if (!this._camera) {
|
let camera = preview ? this._previewCamera : this._camera;
|
||||||
this._camera = root.createCamera();
|
if (!camera) {
|
||||||
if (!this._camera) return null;
|
camera = root.createCamera();
|
||||||
this._camera.initialize({
|
if (!camera) return null;
|
||||||
|
camera.initialize({
|
||||||
name: cameraNode.name,
|
name: cameraNode.name,
|
||||||
node: cameraNode,
|
node: cameraNode,
|
||||||
projection: CameraProjection.PERSPECTIVE,
|
projection: CameraProjection.PERSPECTIVE,
|
||||||
window: EDITOR ? root && root.mainWindow : root && root.tempWindow,
|
window: preview || EDITOR ? root.mainWindow : root.tempWindow,
|
||||||
priority: 0,
|
priority: 0,
|
||||||
cameraType: CameraType.DEFAULT,
|
cameraType: CameraType.DEFAULT,
|
||||||
trackingType: TrackingType.NO_TRACKING,
|
trackingType: TrackingType.NO_TRACKING,
|
||||||
});
|
});
|
||||||
|
if (preview) {
|
||||||
|
this._previewCamera = camera;
|
||||||
|
} else {
|
||||||
|
this._camera = camera;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
this._camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
|
camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
|
||||||
this._camera.fovAxis = CameraFOVAxis.VERTICAL;
|
camera.fovAxis = CameraFOVAxis.VERTICAL;
|
||||||
this._camera.fov = toRadian(90);
|
camera.fov = toRadian(90);
|
||||||
this._camera.orthoHeight = 10;
|
camera.orthoHeight = 10;
|
||||||
this._camera.nearClip = 1;
|
camera.nearClip = 1;
|
||||||
this._camera.farClip = 1000;
|
camera.farClip = 1000;
|
||||||
this._camera.clearColor = this._backgroundColor;
|
camera.clearColor = this._backgroundColor;
|
||||||
this._camera.clearDepth = 1.0;
|
camera.clearDepth = 1.0;
|
||||||
this._camera.clearStencil = 0.0;
|
camera.clearStencil = 0.0;
|
||||||
this._camera.clearFlag = this._clearFlag;
|
camera.clearFlag = this._clearFlag;
|
||||||
this._camera.visibility = this._visibility;
|
camera.visibility = this._visibility;
|
||||||
this._camera.aperture = CameraAperture.F16_0;
|
camera.aperture = CameraAperture.F16_0;
|
||||||
this._camera.shutter = CameraShutter.D125;
|
camera.shutter = CameraShutter.D125;
|
||||||
this._camera.iso = CameraISO.ISO100;
|
camera.iso = CameraISO.ISO100;
|
||||||
return this._camera;
|
return camera;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _resetCameraParams (): void {
|
private _resetCameraParams (): void {
|
||||||
@@ -478,10 +510,10 @@ export class ReflectionProbe {
|
|||||||
return rt;
|
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);
|
const offset = Vec3.dot(this.node.worldPosition, this.node.up);
|
||||||
this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset);
|
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);
|
Vec3.transformQuat(this._forward, Vec3.FORWARD, sourceCamera.node.worldRotation);
|
||||||
this._reflect(this._forward, this._forward, this.node.up, 0);
|
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);
|
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
|
// 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));
|
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());
|
viewSpaceProbe.transformMat4(targetCamera.matView.clone().invert().transpose());
|
||||||
this.camera.calculateObliqueMat(viewSpaceProbe);
|
targetCamera.calculateObliqueMat(viewSpaceProbe);
|
||||||
}
|
}
|
||||||
|
|
||||||
private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 {
|
private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 {
|
||||||
|
|||||||
@@ -102,6 +102,9 @@ export class SphereLight extends Light {
|
|||||||
* @en The luminance of the light source in LDR mode
|
* @en The luminance of the light source in LDR mode
|
||||||
* @zh LDR 模式下光源的亮度
|
* @zh LDR 模式下光源的亮度
|
||||||
*/
|
*/
|
||||||
|
get luminanceLDR (): number {
|
||||||
|
return this._luminanceLDR;
|
||||||
|
}
|
||||||
set luminanceLDR (value: number) {
|
set luminanceLDR (value: number) {
|
||||||
this._luminanceLDR = value;
|
this._luminanceLDR = value;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,6 @@
|
|||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
****************************************************************************/
|
****************************************************************************/
|
||||||
import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx';
|
import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx';
|
||||||
import { genHashValue } from './define';
|
|
||||||
import { VectorGraphColorMap } from './effect';
|
import { VectorGraphColorMap } from './effect';
|
||||||
import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph';
|
import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph';
|
||||||
import { LayoutGraphData } from './layout-graph';
|
import { LayoutGraphData } from './layout-graph';
|
||||||
@@ -199,7 +198,6 @@ class PassVisitor implements RenderGraphVisitor {
|
|||||||
resourceGraph.visitVertex(this._resVisitor, vertID);
|
resourceGraph.visitVertex(this._resVisitor, vertID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
genHashValue(pass);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
applyID (id: number, resId: number): void {
|
applyID (id: number, resId: number): void {
|
||||||
@@ -233,7 +231,21 @@ class PassVisitor implements RenderGraphVisitor {
|
|||||||
compute (value: ComputePass): void {
|
compute (value: ComputePass): void {
|
||||||
this._currPass = value;
|
this._currPass = value;
|
||||||
const rg = context.renderGraph;
|
const rg = context.renderGraph;
|
||||||
|
if (rg.getValid(this.passID)) {
|
||||||
|
// Avoid revisiting a valid pass and recursive dependency cycles.
|
||||||
|
return;
|
||||||
|
}
|
||||||
rg.setValid(this.passID, true);
|
rg.setValid(this.passID, true);
|
||||||
|
// Trace READ dependencies only; WRITE dependencies are produced by this pass.
|
||||||
|
const resourceGraph = this.context.resourceGraph;
|
||||||
|
for (const [computeName, cViews] of value.computeViews) {
|
||||||
|
if (!cViews.length || cViews[0].accessType !== AccessType.READ) continue;
|
||||||
|
const vertID = resourceGraph.find(computeName);
|
||||||
|
if (vertID !== 0xFFFFFFFF) {
|
||||||
|
this._resVisitor.resID = vertID;
|
||||||
|
resourceGraph.visitVertex(this._resVisitor, vertID);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
resolve (value: ResolvePass): void {
|
resolve (value: ResolvePass): void {
|
||||||
// noop
|
// noop
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ import {
|
|||||||
Device,
|
Device,
|
||||||
deviceManager,
|
deviceManager,
|
||||||
DispatchInfo,
|
DispatchInfo,
|
||||||
|
Feature,
|
||||||
Format,
|
Format,
|
||||||
Framebuffer,
|
Framebuffer,
|
||||||
FramebufferInfo,
|
FramebufferInfo,
|
||||||
@@ -56,9 +57,7 @@ import {
|
|||||||
InputAssemblerInfo,
|
InputAssemblerInfo,
|
||||||
LoadOp,
|
LoadOp,
|
||||||
MemoryUsageBit,
|
MemoryUsageBit,
|
||||||
PipelineBindPoint,
|
|
||||||
PipelineState,
|
PipelineState,
|
||||||
PipelineStateInfo,
|
|
||||||
Rect,
|
Rect,
|
||||||
RenderPass,
|
RenderPass,
|
||||||
RenderPassInfo,
|
RenderPassInfo,
|
||||||
@@ -615,10 +614,17 @@ class DeviceRenderQueue implements RecordingInterface {
|
|||||||
this._devicePass = devicePass;
|
this._devicePass = devicePass;
|
||||||
this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id));
|
this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Creates a blit descriptor for the given blit operation.
|
||||||
|
* @zh 为给定的 blit 操作创建一个 blit 描述符。
|
||||||
|
* @param blit @en The blit operation to create a descriptor for. @zh 要为其创建描述符的 blit 操作。
|
||||||
|
*/
|
||||||
createBlitDesc (blit: Blit): void {
|
createBlitDesc (blit: Blit): void {
|
||||||
if (!this._blitDesc) {
|
if (!this._blitDesc) {
|
||||||
this._blitDesc = new BlitDesc(blit);
|
this._blitDesc = new BlitDesc(blit);
|
||||||
}
|
}
|
||||||
|
this._blitDesc.blit = blit;
|
||||||
this._blitDesc.createScreenQuad();
|
this._blitDesc.createScreenQuad();
|
||||||
this._blitDesc.createStageDescriptor();
|
this._blitDesc.createStageDescriptor();
|
||||||
}
|
}
|
||||||
@@ -1903,26 +1909,23 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor {
|
|||||||
renderScene.preRecord();
|
renderScene.preRecord();
|
||||||
}
|
}
|
||||||
dispatch (value: Dispatch): void {
|
dispatch (value: Dispatch): void {
|
||||||
|
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
|
||||||
let pso: PipelineState | null = null;
|
let pso: PipelineState | null = null;
|
||||||
const devicePass = this.currPass as DeviceComputePass;
|
const devicePass = this.currPass as DeviceComputePass;
|
||||||
const pass = value.material?.passes[value.passID];
|
const pass = value.material?.passes[value.passID];
|
||||||
pass?.update();
|
pass?.update();
|
||||||
const shader = pass?.getShaderVariant();
|
const shader = pass?.getShaderVariant();
|
||||||
|
|
||||||
if (pass !== null && shader !== null) {
|
if (pass && shader) {
|
||||||
const psoInfo = new PipelineStateInfo(
|
pso = PipelineStateManager.getOrCreateComputePipelineState(deviceManager.gfxDevice, pass, shader);
|
||||||
shader,
|
|
||||||
pass?.pipelineLayout,
|
|
||||||
);
|
|
||||||
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
|
|
||||||
pso = deviceManager.gfxDevice.createPipelineState(psoInfo);
|
|
||||||
}
|
}
|
||||||
const cmdBuff = context.commandBuffer;
|
const cmdBuff = context.commandBuffer;
|
||||||
if (pso) {
|
if (pso && pass) {
|
||||||
cmdBuff.bindPipelineState(pso);
|
cmdBuff.bindPipelineState(pso);
|
||||||
const layoutStage = devicePass.renderLayout;
|
const layoutStage = devicePass.renderLayout;
|
||||||
const layoutDesc = layoutStage!.descriptorSet!;
|
const layoutDesc = layoutStage!.descriptorSet!;
|
||||||
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc);
|
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc);
|
||||||
|
cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
|
||||||
}
|
}
|
||||||
|
|
||||||
const gx = value.threadGroupCountX;
|
const gx = value.threadGroupCountX;
|
||||||
@@ -1958,10 +1961,12 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor
|
|||||||
computeSubpass (value: ComputeSubpass): void {
|
computeSubpass (value: ComputeSubpass): void {
|
||||||
// do nothing
|
// do nothing
|
||||||
}
|
}
|
||||||
resolve (value: ResolvePass): void {
|
|
||||||
// do nothing
|
|
||||||
}
|
|
||||||
compute (value: ComputePass): void {
|
compute (value: ComputePass): void {
|
||||||
|
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
|
||||||
|
const cmdBuff = context.commandBuffer;
|
||||||
|
(cmdBuff as any).submitComputePass();
|
||||||
|
}
|
||||||
|
resolve (value: ResolvePass): void {
|
||||||
// do nothing
|
// do nothing
|
||||||
}
|
}
|
||||||
copy (value: CopyPass): void {
|
copy (value: CopyPass): void {
|
||||||
|
|||||||
@@ -195,10 +195,13 @@ function sceneCulling (
|
|||||||
}
|
}
|
||||||
models.push(model);
|
models.push(model);
|
||||||
} else if (probe.probeType === ProbeType.CUBE) {
|
} else if (probe.probeType === ProbeType.CUBE) {
|
||||||
|
if (!wBounds || !model.bakeToReflectionProbe) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (!isVisible(model, visibility)) {
|
if (!isVisible(model, visibility)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (wBounds && isIntersectAABB(wBounds, probe.boundingBox!)) {
|
if (isIntersectAABB(wBounds, probe.boundingBox!)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
models.push(model);
|
models.push(model);
|
||||||
@@ -475,7 +478,8 @@ export class SceneCulling {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Get or create render queue
|
// 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
|
// add render queue query
|
||||||
const renderQueueQuery = this.cullingPools.renderQueueQueryRecycle.add();
|
const renderQueueQuery = this.cullingPools.renderQueueQueryRecycle.add();
|
||||||
@@ -556,7 +560,11 @@ export class SceneCulling {
|
|||||||
|
|
||||||
private executeSphereLightCulling (light: SphereLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
|
private executeSphereLightCulling (light: SphereLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
|
||||||
const lightAABB = light.aabb;
|
const lightAABB = light.aabb;
|
||||||
|
const visibility = light.visibility;
|
||||||
for (const model of frustumCullingResult) {
|
for (const model of frustumCullingResult) {
|
||||||
|
if (!isVisible(model, visibility)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const modelBounds = model.worldBounds;
|
const modelBounds = model.worldBounds;
|
||||||
if (!modelBounds || intersect.aabbWithAABB(modelBounds, lightAABB)) {
|
if (!modelBounds || intersect.aabbWithAABB(modelBounds, lightAABB)) {
|
||||||
lightBoundsCullingResult.push(model);
|
lightBoundsCullingResult.push(model);
|
||||||
@@ -567,7 +575,11 @@ export class SceneCulling {
|
|||||||
private executeSpotLightCulling (light: SpotLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
|
private executeSpotLightCulling (light: SpotLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
|
||||||
const lightAABB = light.aabb;
|
const lightAABB = light.aabb;
|
||||||
const lightFrustum: Frustum = light.frustum;
|
const lightFrustum: Frustum = light.frustum;
|
||||||
|
const visibility = light.visibility;
|
||||||
for (const model of frustumCullingResult) {
|
for (const model of frustumCullingResult) {
|
||||||
|
if (!isVisible(model, visibility)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const modelBounds = model.worldBounds;
|
const modelBounds = model.worldBounds;
|
||||||
if (!modelBounds || (intersect.aabbWithAABB(lightAABB, modelBounds) && intersect.aabbFrustum(modelBounds, lightFrustum))) {
|
if (!modelBounds || (intersect.aabbWithAABB(lightAABB, modelBounds) && intersect.aabbFrustum(modelBounds, lightFrustum))) {
|
||||||
lightBoundsCullingResult.push(model);
|
lightBoundsCullingResult.push(model);
|
||||||
@@ -577,7 +589,11 @@ export class SceneCulling {
|
|||||||
|
|
||||||
private executePointLightCulling (light: PointLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
|
private executePointLightCulling (light: PointLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
|
||||||
const lightAABB = light.aabb;
|
const lightAABB = light.aabb;
|
||||||
|
const visibility = light.visibility;
|
||||||
for (const model of frustumCullingResult) {
|
for (const model of frustumCullingResult) {
|
||||||
|
if (!isVisible(model, visibility)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const modelBounds = model.worldBounds;
|
const modelBounds = model.worldBounds;
|
||||||
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
|
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
|
||||||
lightBoundsCullingResult.push(model);
|
lightBoundsCullingResult.push(model);
|
||||||
@@ -590,8 +606,12 @@ export class SceneCulling {
|
|||||||
frustumCullingResult: Array<Model>,
|
frustumCullingResult: Array<Model>,
|
||||||
lightBoundsCullingResult: Array<Model>,
|
lightBoundsCullingResult: Array<Model>,
|
||||||
): void {
|
): void {
|
||||||
|
const visibility = light.visibility;
|
||||||
rangedDirLightBoundingBox.transform(light.node!.worldMatrix, null, null, null, lightAABB);
|
rangedDirLightBoundingBox.transform(light.node!.worldMatrix, null, null, null, lightAABB);
|
||||||
for (const model of frustumCullingResult) {
|
for (const model of frustumCullingResult) {
|
||||||
|
if (!isVisible(model, visibility)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const modelBounds = model.worldBounds;
|
const modelBounds = model.worldBounds;
|
||||||
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
|
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
|
||||||
lightBoundsCullingResult.push(model);
|
lightBoundsCullingResult.push(model);
|
||||||
@@ -817,11 +837,20 @@ export class LightResource {
|
|||||||
this.lightIndex.clear();
|
this.lightIndex.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Adds a light to the light buffer and returns its byte offset.
|
||||||
|
* @zh 将光源添加到光源缓冲区,并返回其字节偏移量。
|
||||||
|
* @param light @en The light to add. @zh 要添加的光源。
|
||||||
|
* @param bHDR @en Whether HDR rendering is enabled. @zh 是否启用 HDR 渲染。
|
||||||
|
* @param exposure @en The camera exposure value. @zh 相机曝光值。
|
||||||
|
* @param shadowInfo @en The shadow settings, or null if shadows are disabled. @zh 阴影设置,若禁用阴影则为 null。
|
||||||
|
* @returns @en The byte offset of the light in the light buffer. @zh 光源在光源缓冲区中的字节偏移量。
|
||||||
|
*/
|
||||||
addLight (light: Light, bHDR: boolean, exposure: number, shadowInfo: Shadows | null): number {
|
addLight (light: Light, bHDR: boolean, exposure: number, shadowInfo: Shadows | null): number {
|
||||||
// Already added
|
// Already added
|
||||||
const existingLightID = this.lightIndex.get(light);
|
const existingLightID = this.lightIndex.get(light);
|
||||||
if (existingLightID !== undefined) {
|
if (existingLightID !== undefined) {
|
||||||
return existingLightID;
|
return existingLightID * this.elementSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.lightBuffer) {
|
if (!this.lightBuffer) {
|
||||||
|
|||||||
@@ -258,9 +258,19 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
|
|||||||
|
|
||||||
addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void {
|
addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void {
|
||||||
const lightTarget = light.light;
|
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 {
|
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(
|
const sceneData = renderGraphPool.createSceneData(
|
||||||
scene || camera.scene,
|
scene || camera.scene,
|
||||||
camera,
|
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 && !(sceneFlags & SceneFlags.SHADOW_CASTER) ? CullingFlags.CAMERA_FRUSTUM | CullingFlags.LIGHT_BOUNDS : CullingFlags.CAMERA_FRUSTUM,
|
||||||
light,
|
light,
|
||||||
);
|
);
|
||||||
|
if (lightInfo) {
|
||||||
|
sceneData.light.reset(lightInfo.light, lightInfo.level, lightInfo.culledByLight, lightInfo.probe);
|
||||||
|
}
|
||||||
const renderData = renderGraphPool.createRenderData();
|
const renderData = renderGraphPool.createRenderData();
|
||||||
const sceneId = this._renderGraph.addVertex<RenderGraphValue.Scene>(RenderGraphValue.Scene, sceneData, 'Scene', '', renderData, !DEBUG, this._vertID);
|
const sceneId = this._renderGraph.addVertex<RenderGraphValue.Scene>(RenderGraphValue.Scene, sceneData, 'Scene', '', renderData, !DEBUG, this._vertID);
|
||||||
if (!(sceneFlags & SceneFlags.NON_BUILTIN)) {
|
if (!(sceneFlags & SceneFlags.NON_BUILTIN)) {
|
||||||
@@ -851,7 +864,11 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild
|
|||||||
this._renderGraph.setName(this._vertID, name);
|
this._renderGraph.setName(this._vertID, name);
|
||||||
}
|
}
|
||||||
addTexture (name: string, slotName: string, sampler: Sampler | null = null): void {
|
addTexture (name: string, slotName: string, sampler: Sampler | null = null): void {
|
||||||
throw new Error('Method not implemented.');
|
this._addComputeResource(name, AccessType.READ, slotName);
|
||||||
|
if (sampler) {
|
||||||
|
const descriptorID = this._lg.attributeIndex.get(slotName)!;
|
||||||
|
this._data.samplers.set(descriptorID, sampler);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
addStorageBuffer (name: string, accessType: AccessType, slotName: string): void {
|
addStorageBuffer (name: string, accessType: AccessType, slotName: string): void {
|
||||||
this._addComputeResource(name, accessType, slotName);
|
this._addComputeResource(name, accessType, slotName);
|
||||||
@@ -1650,13 +1667,16 @@ export class WebPipeline extends WebSetter implements BasicPipeline {
|
|||||||
this._compiler = new Compiler(this, this._renderGraph, this._resourceGraph, this._lg);
|
this._compiler = new Compiler(this, this._renderGraph, this._resourceGraph, this._lg);
|
||||||
}
|
}
|
||||||
this._compiler.compile(this._renderGraph);
|
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 {
|
execute (): void {
|
||||||
|
|||||||
@@ -1264,15 +1264,6 @@ export class WebProgramLibrary implements ProgramLibrary {
|
|||||||
if (passSet) {
|
if (passSet) {
|
||||||
info.setLayouts.push(passSet);
|
info.setLayouts.push(passSet);
|
||||||
}
|
}
|
||||||
const phaseSet = getDescriptorSetLayout(
|
|
||||||
this.layoutGraph,
|
|
||||||
subpassOrPassID,
|
|
||||||
phaseID,
|
|
||||||
UpdateFrequency.PER_PHASE,
|
|
||||||
);
|
|
||||||
if (phaseSet) {
|
|
||||||
info.setLayouts.push(phaseSet);
|
|
||||||
}
|
|
||||||
const batchSet = getProgramDescriptorSetLayout(
|
const batchSet = getProgramDescriptorSetLayout(
|
||||||
device,
|
device,
|
||||||
lg,
|
lg,
|
||||||
@@ -1293,6 +1284,15 @@ export class WebProgramLibrary implements ProgramLibrary {
|
|||||||
if (instanceSet) {
|
if (instanceSet) {
|
||||||
info.setLayouts.push(instanceSet);
|
info.setLayouts.push(instanceSet);
|
||||||
}
|
}
|
||||||
|
const phaseSet = getDescriptorSetLayout(
|
||||||
|
this.layoutGraph,
|
||||||
|
subpassOrPassID,
|
||||||
|
phaseID,
|
||||||
|
UpdateFrequency.PER_PHASE,
|
||||||
|
);
|
||||||
|
if (phaseSet) {
|
||||||
|
info.setLayouts.push(phaseSet);
|
||||||
|
}
|
||||||
programData.pipelineLayout = device.createPipelineLayout(info);
|
programData.pipelineLayout = device.createPipelineLayout(info);
|
||||||
return programData.pipelineLayout;
|
return programData.pipelineLayout;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,8 +28,9 @@ import { UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMA
|
|||||||
UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, ENABLE_PROBE_BLEND,
|
UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, ENABLE_PROBE_BLEND,
|
||||||
IRenderPass,
|
IRenderPass,
|
||||||
getPassPool } from './define';
|
getPassPool } from './define';
|
||||||
import { BufferUsageBit, MemoryUsageBit, Device, Texture, InputAssembler, InputAssemblerInfo,
|
import { BufferUsageBit, MemoryUsageBit, Device, InputAssembler, InputAssemblerInfo,
|
||||||
Attribute, Buffer, BufferInfo, CommandBuffer, Shader, DescriptorSet } from '../gfx';
|
Attribute, Buffer, BufferInfo, CommandBuffer, Shader, DescriptorSet } from '../gfx';
|
||||||
|
import type { Texture } from '../gfx';
|
||||||
import { RecyclePool } from '../core/memop';
|
import { RecyclePool } from '../core/memop';
|
||||||
|
|
||||||
export function instancingCompareFn (l: InstancedBuffer, r: InstancedBuffer): number {
|
export function instancingCompareFn (l: InstancedBuffer, r: InstancedBuffer): number {
|
||||||
@@ -65,6 +66,7 @@ export class InstancedBuffer {
|
|||||||
public sortRender: IRenderPass;
|
public sortRender: IRenderPass;
|
||||||
private declare _passPool: RecyclePool<IRenderPass>;
|
private declare _passPool: RecyclePool<IRenderPass>;
|
||||||
private declare _device: Device;
|
private declare _device: Device;
|
||||||
|
private readonly _instanceMap = new Map<string, IInstancedItem[]>();
|
||||||
constructor (pass: Pass) {
|
constructor (pass: Pass) {
|
||||||
this._device = pass.device;
|
this._device = pass.device;
|
||||||
this.pass = pass;
|
this.pass = pass;
|
||||||
@@ -81,6 +83,7 @@ export class InstancedBuffer {
|
|||||||
});
|
});
|
||||||
this._passPool.reset();
|
this._passPool.reset();
|
||||||
this.instances.length = 0;
|
this.instances.length = 0;
|
||||||
|
this._instanceMap.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null): void {
|
public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null): void {
|
||||||
@@ -106,72 +109,124 @@ export class InstancedBuffer {
|
|||||||
this.sortRender.hash = hash;
|
this.sortRender.hash = hash;
|
||||||
this.sortRender.shaderId = shader.typedID;
|
this.sortRender.shaderId = shader.typedID;
|
||||||
this.sortRender.passIdx = passIdx;
|
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
|
const key = `${sourceIA.indexBuffer?.objectID ?? 0}/${lightingMap.objectID}/${useReflectionProbeType}/`
|
||||||
if (instance.lightingMap.objectID !== lightingMap.objectID) {
|
+ `${reflectionProbeCubemap.objectID}/${reflectionProbePlanarMap.objectID}/`
|
||||||
continue;
|
+ `${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
|
||||||
|
const requiredCapacity = instance.count + 1;
|
||||||
|
const targetCapacity = Math.min(Math.max(instance.capacity << 1, requiredCapacity), MAX_CAPACITY);
|
||||||
|
const targetSize = instance.stride * targetCapacity;
|
||||||
|
instance.vb.resize(targetSize);
|
||||||
|
if (instance.vb.size < targetSize) {
|
||||||
|
const requiredSize = instance.stride * requiredCapacity;
|
||||||
|
if (instance.vb.size < requiredSize) {
|
||||||
|
instance.vb.resize(requiredSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
instance.capacity = Math.floor(instance.vb.size / instance.stride);
|
||||||
|
if (instance.count >= instance.capacity) {
|
||||||
|
instance.count = instance.capacity;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const newSize = instance.stride * instance.capacity;
|
||||||
|
if (newSize > instance.data.byteLength) {
|
||||||
|
const oldData = instance.data;
|
||||||
|
instance.data = new Uint8Array(newSize);
|
||||||
|
instance.data.set(oldData.subarray(0, instance.count * instance.stride));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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(
|
const vb = this._device.createBuffer(new BufferInfo(
|
||||||
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
|
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
|
||||||
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
|
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
|
||||||
stride * INITIAL_CAPACITY,
|
newSize,
|
||||||
stride,
|
stride,
|
||||||
));
|
));
|
||||||
const data = new Uint8Array(stride * INITIAL_CAPACITY);
|
const data = new Uint8Array(newSize);
|
||||||
const vertexBuffers = sourceIA.vertexBuffers.slice();
|
const vertexBuffers = sourceIA.vertexBuffers.slice();
|
||||||
const attributes = sourceIA.attributes.slice();
|
const attributes = sourceIA.attributes.slice();
|
||||||
const indexBuffer = sourceIA.indexBuffer;
|
const indexBuffer = sourceIA.indexBuffer;
|
||||||
|
|
||||||
for (let i = 0; i < attrs.attributes.length; i++) {
|
for (let i = 0; i < instancedAttributes.length; i++) {
|
||||||
const attr = attrs.attributes[i];
|
const attr = instancedAttributes[i];
|
||||||
const newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
|
const newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
|
||||||
attributes.push(newAttr);
|
attributes.push(newAttr);
|
||||||
}
|
}
|
||||||
data.set(attrs.buffer);
|
data.set(instanceData);
|
||||||
|
|
||||||
vertexBuffers.push(vb);
|
vertexBuffers.push(vb);
|
||||||
const iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
|
const iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
|
||||||
const ia = this._device.createInputAssembler(iaInfo);
|
const ia = this._device.createInputAssembler(iaInfo);
|
||||||
// eslint-disable-next-line max-len
|
const instance = {
|
||||||
this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, lightingMap, reflectionProbeCubemap, reflectionProbePlanarMap, useReflectionProbeType, reflectionProbeBlendCubemap });
|
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;
|
this.hasPendingModels = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,7 +235,7 @@ export class InstancedBuffer {
|
|||||||
const instance = this.instances[i];
|
const instance = this.instances[i];
|
||||||
if (!instance.count) { continue; }
|
if (!instance.count) { continue; }
|
||||||
instance.ia.instanceCount = instance.count;
|
instance.ia.instanceCount = instance.count;
|
||||||
cmdBuff.updateBuffer(instance.vb, instance.data);
|
cmdBuff.updateBuffer(instance.vb, instance.data.buffer as ArrayBuffer, instance.count * instance.stride);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo } from '../gfx';
|
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo, PipelineBindPoint } from '../gfx';
|
||||||
import { Pass } from '../render-scene/core/pass';
|
import { Pass } from '../render-scene/core/pass';
|
||||||
|
|
||||||
export class PipelineStateManager {
|
export class PipelineStateManager {
|
||||||
@@ -30,6 +30,8 @@ export class PipelineStateManager {
|
|||||||
|
|
||||||
private static _PSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
|
private static _PSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
|
||||||
|
|
||||||
|
private static _computePSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
|
||||||
|
|
||||||
// pass is only needed on TS.
|
// pass is only needed on TS.
|
||||||
static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState {
|
static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState {
|
||||||
const hash1 = pass.hash;
|
const hash1 = pass.hash;
|
||||||
@@ -59,4 +61,33 @@ export class PipelineStateManager {
|
|||||||
|
|
||||||
return pso;
|
return pso;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @en Get or create a compute pipeline state.
|
||||||
|
* A compute pipeline only depends on the shader variant and the pipeline layout,
|
||||||
|
* both carried by the pass, so the cache key is `pass.hash ^ shader.typedID`,
|
||||||
|
* mirroring the graphics-side hash mechanism without renderPass/inputState factors.
|
||||||
|
* @zh 获取或创建计算管线状态。
|
||||||
|
* 计算管线仅依赖于着色器变体与管线布局(均由 pass 携带),
|
||||||
|
* 因此缓存键为 `pass.hash ^ shader.typedID`,与图形侧哈希机制一致但不包含 renderPass/顶点布局因子。
|
||||||
|
*/
|
||||||
|
static getOrCreateComputePipelineState (device: Device, pass: Pass, shader: Shader): PipelineState {
|
||||||
|
const hash1 = pass.hash;
|
||||||
|
const hash2 = shader.typedID;
|
||||||
|
|
||||||
|
const newHash = hash1 ^ hash2;
|
||||||
|
let pso = this._computePSOHashMap.get(newHash);
|
||||||
|
if (!pso) {
|
||||||
|
const pipelineLayout = pass.pipelineLayout;
|
||||||
|
const psoInfo = new PipelineStateInfo(
|
||||||
|
shader,
|
||||||
|
pipelineLayout,
|
||||||
|
);
|
||||||
|
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
|
||||||
|
pso = device.createPipelineState(psoInfo);
|
||||||
|
this._computePSOHashMap.set(newHash, pso);
|
||||||
|
}
|
||||||
|
|
||||||
|
return pso;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ import { PipelineStateManager } from './pipeline-state-manager';
|
|||||||
import { Model, Camera, SubModel } from '../render-scene/scene';
|
import { Model, Camera, SubModel } from '../render-scene/scene';
|
||||||
import { RenderInstancedQueue } from './render-instanced-queue';
|
import { RenderInstancedQueue } from './render-instanced-queue';
|
||||||
import { ShadowType } from '../render-scene/scene/shadows';
|
import { ShadowType } from '../render-scene/scene/shadows';
|
||||||
import { Layers } from '../scene-graph/layers';
|
|
||||||
import { PipelineRuntime } from './custom/pipeline';
|
import { PipelineRuntime } from './custom/pipeline';
|
||||||
import { BatchingSchemes, Pass } from '../render-scene/core/pass';
|
import { BatchingSchemes, Pass } from '../render-scene/core/pass';
|
||||||
import { getPhaseID } from './pass-phase';
|
import { getPhaseID } from './pass-phase';
|
||||||
@@ -83,18 +82,16 @@ export class PlanarShadowQueue {
|
|||||||
|
|
||||||
const scene = camera.scene!;
|
const scene = camera.scene!;
|
||||||
const frustum = camera.frustum;
|
const frustum = camera.frustum;
|
||||||
const shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 0;
|
const shadowVisible = camera.visibility !== 0;
|
||||||
if (!scene.mainLight || !shadowVisible) { return; }
|
if (!scene.mainLight || !shadowVisible) { return; }
|
||||||
|
|
||||||
const models = scene.models;
|
const models = scene.models;
|
||||||
const visibility = camera.visibility;
|
|
||||||
for (let i = 0; i < models.length; i++) {
|
for (let i = 0; i < models.length; i++) {
|
||||||
const model = models[i];
|
const model = models[i];
|
||||||
if (scene.isCulledByLod(camera, model)) {
|
if (scene.isCulledByLod(camera, model)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (model.enabled && model.node && model.castShadow
|
if (model.enabled && model.node && model.castShadow) {
|
||||||
&& (model.node && ((visibility & model.node.layer) === model.node.layer))) {
|
|
||||||
this._castModels.push(model);
|
this._castModels.push(model);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ import { IRenderFlowInfo, RenderFlow } from '../render-flow';
|
|||||||
import { ReflectionProbeStage } from './reflection-probe-stage';
|
import { ReflectionProbeStage } from './reflection-probe-stage';
|
||||||
import { RenderFlowTag } from '../pipeline-serialization';
|
import { RenderFlowTag } from '../pipeline-serialization';
|
||||||
import { RenderPipeline } from '../render-pipeline';
|
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 { ProbeType, ReflectionProbe } from '../../render-scene/scene/reflection-probe';
|
||||||
import { cclegacy } from '../../core';
|
import { cclegacy } from '../../core';
|
||||||
|
|
||||||
@@ -65,7 +65,13 @@ export class ReflectionProbeFlow extends RenderFlow {
|
|||||||
const probes = cclegacy.internal.reflectionProbeManager.getProbes() as ReflectionProbe[];
|
const probes = cclegacy.internal.reflectionProbeManager.getProbes() as ReflectionProbe[];
|
||||||
for (let i = 0; i < probes.length; i++) {
|
for (let i = 0; i < probes.length; i++) {
|
||||||
if (probes[i].needRender) {
|
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]);
|
this._renderStage(camera, probes[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,12 +81,12 @@ export class ReflectionProbeFlow extends RenderFlow {
|
|||||||
public destroy (): void {
|
public destroy (): void {
|
||||||
super.destroy();
|
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++) {
|
for (let i = 0; i < this._stages.length; i++) {
|
||||||
const probeStage = this._stages[i] as ReflectionProbeStage;
|
const probeStage = this._stages[i] as ReflectionProbeStage;
|
||||||
if (probe.probeType === ProbeType.PLANAR) {
|
if (probe.probeType === ProbeType.PLANAR) {
|
||||||
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, null);
|
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, null);
|
||||||
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer);
|
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer, reflectionCamera);
|
||||||
probeStage.render(camera);
|
probeStage.render(camera);
|
||||||
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, probe.realtimePlanarTexture!.getGFXTexture());
|
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, probe.realtimePlanarTexture!.getGFXTexture());
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ export class ReflectionProbeStage extends RenderStage {
|
|||||||
private _frameBuffer: Framebuffer | null = null;
|
private _frameBuffer: Framebuffer | null = null;
|
||||||
private _renderArea = new Rect();
|
private _renderArea = new Rect();
|
||||||
private _probe: ReflectionProbe | null = null;
|
private _probe: ReflectionProbe | null = null;
|
||||||
|
private _reflectionCamera: Camera | null = null;
|
||||||
private _probeRenderQueue!: RenderReflectionProbeQueue;
|
private _probeRenderQueue!: RenderReflectionProbeQueue;
|
||||||
private _rgbeColor = new Vec3();
|
private _rgbeColor = new Vec3();
|
||||||
|
|
||||||
@@ -68,9 +69,10 @@ export class ReflectionProbeStage extends RenderStage {
|
|||||||
* @param probe
|
* @param probe
|
||||||
* @param frameBuffer
|
* @param frameBuffer
|
||||||
*/
|
*/
|
||||||
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer): void {
|
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer, reflectionCamera?: Camera): void {
|
||||||
this._probe = probe;
|
this._probe = probe;
|
||||||
this._frameBuffer = frameBuffer;
|
this._frameBuffer = frameBuffer;
|
||||||
|
this._reflectionCamera = reflectionCamera ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public destroy (): void {
|
public destroy (): void {
|
||||||
@@ -108,8 +110,9 @@ export class ReflectionProbeStage extends RenderStage {
|
|||||||
public render (camera: Camera): void {
|
public render (camera: Camera): void {
|
||||||
const pipeline = this._pipeline;
|
const pipeline = this._pipeline;
|
||||||
const cmdBuff = pipeline.commandBuffers[0];
|
const cmdBuff = pipeline.commandBuffers[0];
|
||||||
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff);
|
const probeCamera = this._reflectionCamera ?? this._probe!.camera;
|
||||||
pipeline.pipelineUBO.updateCameraUBO(this._probe!.camera);
|
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff, probeCamera);
|
||||||
|
pipeline.pipelineUBO.updateCameraUBO(probeCamera);
|
||||||
|
|
||||||
this._renderArea.x = 0;
|
this._renderArea.x = 0;
|
||||||
this._renderArea.y = 0;
|
this._renderArea.y = 0;
|
||||||
@@ -118,10 +121,10 @@ export class ReflectionProbeStage extends RenderStage {
|
|||||||
|
|
||||||
const renderPass = this._frameBuffer!.renderPass;
|
const renderPass = this._frameBuffer!.renderPass;
|
||||||
|
|
||||||
if (this._probe!.camera.clearFlag & ClearFlagBit.COLOR) {
|
if (probeCamera.clearFlag & ClearFlagBit.COLOR) {
|
||||||
this._rgbeColor.x = this._probe!.camera.clearColor.x;
|
this._rgbeColor.x = probeCamera.clearColor.x;
|
||||||
this._rgbeColor.y = this._probe!.camera.clearColor.y;
|
this._rgbeColor.y = probeCamera.clearColor.y;
|
||||||
this._rgbeColor.z = this._probe!.camera.clearColor.z;
|
this._rgbeColor.z = probeCamera.clearColor.z;
|
||||||
const rgbe = packRGBE(this._rgbeColor);
|
const rgbe = packRGBE(this._rgbeColor);
|
||||||
colors[0].x = rgbe.x;
|
colors[0].x = rgbe.x;
|
||||||
colors[0].y = rgbe.y;
|
colors[0].y = rgbe.y;
|
||||||
@@ -134,8 +137,8 @@ export class ReflectionProbeStage extends RenderStage {
|
|||||||
this._frameBuffer!,
|
this._frameBuffer!,
|
||||||
this._renderArea,
|
this._renderArea,
|
||||||
colors,
|
colors,
|
||||||
this._probe!.camera.clearDepth,
|
probeCamera.clearDepth,
|
||||||
this._probe!.camera.clearStencil,
|
probeCamera.clearStencil,
|
||||||
);
|
);
|
||||||
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
|
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
|
||||||
|
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ export class RenderAdditiveLightQueue {
|
|||||||
private declare _lightBuffer: Buffer;
|
private declare _lightBuffer: Buffer;
|
||||||
private declare _firstLightBufferView: Buffer;
|
private declare _firstLightBufferView: Buffer;
|
||||||
private declare _lightBufferData: Float32Array;
|
private declare _lightBufferData: Float32Array;
|
||||||
private _instancedQueues: RenderInstancedQueue[] = [];
|
private _instancedQueues: (RenderInstancedQueue | undefined)[] = [];
|
||||||
private _lightMeterScale = 10000.0;
|
private _lightMeterScale = 10000.0;
|
||||||
|
|
||||||
constructor (pipeline: PipelineRuntime) {
|
constructor (pipeline: PipelineRuntime) {
|
||||||
@@ -151,7 +151,9 @@ export class RenderAdditiveLightQueue {
|
|||||||
|
|
||||||
public clear (): void {
|
public clear (): void {
|
||||||
this._instancedQueues.forEach((instancedQueue) => {
|
this._instancedQueues.forEach((instancedQueue) => {
|
||||||
instancedQueue.clear();
|
if (instancedQueue) {
|
||||||
|
instancedQueue.clear();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
this._instancedQueues.length = 0;
|
this._instancedQueues.length = 0;
|
||||||
|
|
||||||
@@ -196,7 +198,7 @@ export class RenderAdditiveLightQueue {
|
|||||||
|
|
||||||
this._lightCulling(model, validPunctualLights);
|
this._lightCulling(model, validPunctualLights);
|
||||||
|
|
||||||
if (!_lightIndices.length && validPunctualLights.length > 0) { continue; }
|
if (!_lightIndices.length) { continue; }
|
||||||
|
|
||||||
for (let j = 0; j < subModels.length; j++) {
|
for (let j = 0; j < subModels.length; j++) {
|
||||||
const lightPassIdx = _lightPassIndices[j];
|
const lightPassIdx = _lightPassIndices[j];
|
||||||
@@ -219,15 +221,14 @@ export class RenderAdditiveLightQueue {
|
|||||||
public gatherLightPasses (camera: Camera, cmdBuff: CommandBuffer, passLayout = 'default'): void {
|
public gatherLightPasses (camera: Camera, cmdBuff: CommandBuffer, passLayout = 'default'): void {
|
||||||
this.clear();
|
this.clear();
|
||||||
|
|
||||||
const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
|
|
||||||
if (!validPunctualLights.length) {
|
|
||||||
this._bindForwardAddLight(validPunctualLights, passLayout);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._updateUBOs(camera, cmdBuff);
|
this._updateUBOs(camera, cmdBuff);
|
||||||
this._updateLightDescriptorSet(camera, cmdBuff);
|
this._updateLightDescriptorSet(camera, cmdBuff);
|
||||||
|
|
||||||
|
const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
|
||||||
|
if (!validPunctualLights.length) { return; }
|
||||||
|
|
||||||
this._bindForwardAddLight(validPunctualLights, passLayout);
|
this._bindForwardAddLight(validPunctualLights, passLayout);
|
||||||
|
|
||||||
// only for instanced and batched, no light culling applied
|
// only for instanced and batched, no light culling applied
|
||||||
for (let l = 0; l < validPunctualLights.length; l++) {
|
for (let l = 0; l < validPunctualLights.length; l++) {
|
||||||
const light = validPunctualLights[l];
|
const light = validPunctualLights[l];
|
||||||
@@ -236,17 +237,21 @@ export class RenderAdditiveLightQueue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this._instancedQueues.forEach((instancedQueue) => {
|
this._instancedQueues.forEach((instancedQueue) => {
|
||||||
instancedQueue.uploadBuffers(cmdBuff);
|
if (instancedQueue) {
|
||||||
|
instancedQueue.uploadBuffers(cmdBuff);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void {
|
public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void {
|
||||||
const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager;
|
const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager;
|
||||||
for (let j = 0; j < this._instancedQueues.length; ++j) {
|
for (let j = 0; j < this._instancedQueues.length; ++j) {
|
||||||
|
const queue = this._instancedQueues[j];
|
||||||
|
if (!queue) { continue; }
|
||||||
const light = this._instancedLightPassPool.lights[j];
|
const light = this._instancedLightPassPool.lights[j];
|
||||||
_dynamicOffsets[0] = this._instancedLightPassPool.dynamicOffsets[j];
|
_dynamicOffsets[0] = this._instancedLightPassPool.dynamicOffsets[j];
|
||||||
const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
|
const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
|
||||||
this._instancedQueues[j].recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets);
|
queue.recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let i = 0; i < this._lightPasses.length; i++) {
|
for (let i = 0; i < this._lightPasses.length; i++) {
|
||||||
@@ -315,14 +320,18 @@ export class RenderAdditiveLightQueue {
|
|||||||
const lightIdx = _lightIndices[l];
|
const lightIdx = _lightIndices[l];
|
||||||
const light = validPunctualLights[lightIdx];
|
const light = validPunctualLights[lightIdx];
|
||||||
const visibility = light.visibility;
|
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) {
|
switch (batchingScheme) {
|
||||||
case BatchingSchemes.INSTANCING: {
|
case BatchingSchemes.INSTANCING: {
|
||||||
const buffer = pass.getInstancedBuffer(l);
|
const buffer = pass.getInstancedBuffer(lightIdx);
|
||||||
buffer.merge(subModel, lightPassIdx);
|
buffer.merge(subModel, lightPassIdx);
|
||||||
buffer.dynamicOffsets[0] = this._lightBufferStride;
|
buffer.dynamicOffsets[0] = this._lightBufferStride * lightIdx;
|
||||||
if (!this._instancedQueues[l]) { this._instancedQueues[l] = new RenderInstancedQueue(); }
|
if (this._instancedQueues.length <= lightIdx || !this._instancedQueues[lightIdx]) {
|
||||||
this._instancedQueues[l].queue.add(buffer);
|
this._instancedQueues.length = lightIdx + 1;
|
||||||
|
this._instancedQueues[lightIdx] = new RenderInstancedQueue();
|
||||||
|
}
|
||||||
|
this._instancedQueues[lightIdx]!.queue.add(buffer);
|
||||||
} break;
|
} break;
|
||||||
default:
|
default:
|
||||||
lp!.lights.push(light);
|
lp!.lights.push(light);
|
||||||
@@ -370,9 +379,6 @@ export class RenderAdditiveLightQueue {
|
|||||||
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
|
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
|
||||||
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
|
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
|
||||||
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
|
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
|
||||||
|
|
||||||
// Reserve sphere light shadow interface
|
|
||||||
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case LightType.SPOT: {
|
case LightType.SPOT: {
|
||||||
@@ -437,8 +443,6 @@ export class RenderAdditiveLightQueue {
|
|||||||
this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
|
this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
|
||||||
this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
|
this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
|
||||||
|
|
||||||
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
|
|
||||||
|
|
||||||
// Spot light sampler binding
|
// Spot light sampler binding
|
||||||
if (shadowFrameBufferMap.has(light)) {
|
if (shadowFrameBufferMap.has(light)) {
|
||||||
const texture = shadowFrameBufferMap.get(light)?.colorTextures[0];
|
const texture = shadowFrameBufferMap.get(light)?.colorTextures[0];
|
||||||
@@ -463,15 +467,15 @@ export class RenderAdditiveLightQueue {
|
|||||||
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
|
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
|
||||||
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
|
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
|
||||||
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
|
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
|
||||||
|
|
||||||
// Reserve point light shadow interface
|
|
||||||
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
globalDSManager.update();
|
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
|
||||||
cmdBuff.updateBuffer(descriptorSet.getBuffer(UBOShadow.BINDING)!, this._shadowUBO);
|
|
||||||
|
descriptorSet.update();
|
||||||
|
|
||||||
|
cmdBuff.updateBuffer(descriptorSet.getBuffer(UBOShadow.BINDING)!, this._shadowUBO.buffer, this._shadowUBO.byteLength);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -627,6 +631,6 @@ export class RenderAdditiveLightQueue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cmdBuff.updateBuffer(this._lightBuffer, this._lightBufferData);
|
cmdBuff.updateBuffer(this._lightBuffer, this._lightBufferData.buffer as ArrayBuffer, this._lightBufferData.byteLength);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,13 +79,14 @@ export class RenderReflectionProbeQueue {
|
|||||||
public constructor (pipeline: PipelineRuntime) {
|
public constructor (pipeline: PipelineRuntime) {
|
||||||
this._pipeline = pipeline;
|
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();
|
this.clear();
|
||||||
const scene = camera.scene!;
|
const scene = camera.scene!;
|
||||||
const sceneData = this._pipeline.pipelineSceneData;
|
const sceneData = this._pipeline.pipelineSceneData;
|
||||||
const skybox = sceneData.skybox;
|
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);
|
this.add(skybox.model);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,7 +106,7 @@ export class RenderReflectionProbeQueue {
|
|||||||
if (geometry.intersect.aabbWithAABB(model.worldBounds, probe.boundingBox!)) {
|
if (geometry.intersect.aabbWithAABB(model.worldBounds, probe.boundingBox!)) {
|
||||||
this.add(model);
|
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);
|
this.add(model);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,8 +195,8 @@ export function sceneCulling (sceneData: PipelineSceneData, pipelineUBO: Pipelin
|
|||||||
csmLayerObjects.push(getRenderObject(model, camera));
|
csmLayerObjects.push(getRenderObject(model, camera));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (model.node && ((visibility & model.node.layer) === model.node.layer)
|
if ((model.node && ((visibility & model.node.layer) === model.node.layer))
|
||||||
|| (visibility & model.visFlags)) {
|
|| (visibility & model.visFlags)) {
|
||||||
// frustum culling
|
// frustum culling
|
||||||
if (model.worldBounds && !geometry.intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
|
if (model.worldBounds && !geometry.intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
+2
-2
@@ -25,7 +25,7 @@
|
|||||||
import { cclegacy } from './core/global-exports';
|
import { cclegacy } from './core/global-exports';
|
||||||
import { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
import { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
||||||
import { Device, deviceManager } from './gfx';
|
import { Device, deviceManager } from './gfx';
|
||||||
import { settings, Settings, warnID, Pool, macro, log } from './core';
|
import { settings, Settings, warnID, Pool, macro, log, debug } from './core';
|
||||||
import { PipelineEventProcessor } from './rendering/pipeline-event';
|
import { PipelineEventProcessor } from './rendering/pipeline-event';
|
||||||
import type { Root as JsbRoot } from './root';
|
import type { Root as JsbRoot } from './root';
|
||||||
|
|
||||||
@@ -242,7 +242,7 @@ rootProto.setRenderPipeline = function (customPipeline: boolean) {
|
|||||||
if (customPipeline) {
|
if (customPipeline) {
|
||||||
cclegacy.rendering.createCustomPipeline();
|
cclegacy.rendering.createCustomPipeline();
|
||||||
ppl = oldSetPipeline.call(this, null);
|
ppl = oldSetPipeline.call(this, null);
|
||||||
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||||
} else {
|
} else {
|
||||||
// pipeline should not be created in C++, ._ctor need to be triggered
|
// pipeline should not be created in C++, ._ctor need to be triggered
|
||||||
if (cclegacy.legacy_rendering) {
|
if (cclegacy.legacy_rendering) {
|
||||||
|
|||||||
+3
-3
@@ -23,7 +23,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { USE_XR } from 'internal:constants';
|
import { USE_XR } from 'internal:constants';
|
||||||
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory } from './core';
|
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory, debug } from './core';
|
||||||
import { DebugView } from './rendering/debug-view';
|
import { DebugView } from './rendering/debug-view';
|
||||||
import { Camera, CameraType, Light, Model, TrackingType } from './render-scene/scene';
|
import { Camera, CameraType, Light, Model, TrackingType } from './render-scene/scene';
|
||||||
import type { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
import type { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
|
||||||
@@ -380,11 +380,11 @@ export class Root {
|
|||||||
isCreateDefaultPipeline = true;
|
isCreateDefaultPipeline = true;
|
||||||
this._pipeline = this._customPipeline!;
|
this._pipeline = this._customPipeline!;
|
||||||
// Use default _pipelineEvent
|
// Use default _pipelineEvent
|
||||||
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
|
||||||
} else {
|
} else {
|
||||||
const rppl: (PipelineRuntime & IPipelineEvent) = legacy_rendering.createDefaultPipeline();
|
const rppl: (PipelineRuntime & IPipelineEvent) = legacy_rendering.createDefaultPipeline();
|
||||||
isCreateDefaultPipeline = true;
|
isCreateDefaultPipeline = true;
|
||||||
log(`Using legacy pipeline`);
|
debug(`Using legacy pipeline`);
|
||||||
|
|
||||||
this._classicPipeline = rppl!;
|
this._classicPipeline = rppl!;
|
||||||
this._pipeline = this._classicPipeline;
|
this._pipeline = this._classicPipeline;
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||||
|
|
||||||
|
https://www.cocos.com/
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||||
|
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Runtime-selectable spine instantiation. Used only when both spine-3.8 and spine-4.2 are compiled into
|
||||||
|
// the engine (editor/preview): cc.config.json's moduleOverrides then replaces spine-instantiate.ts with
|
||||||
|
// this file. Unlike the fixed-version files (spine-instantiate-3.8.ts / -4.2.ts), both the 3.8 and 4.2
|
||||||
|
// external references are kept here (so both wasm/asm binaries are bundled), and the matching one is
|
||||||
|
// executed at runtime according to the selected version.
|
||||||
|
// The version comes from the preview boot (game-boot.js / engine-bootstrap.ts), which reads it from
|
||||||
|
// cocos.config.json before engine init and writes globalThis._CC_SPINE_VERSION.
|
||||||
|
|
||||||
|
import { ensureWasmModuleReady } from 'pal/wasm';
|
||||||
|
import { error } from '../../core';
|
||||||
|
import { shouldUseWasmModule, initWasm, initAsmJS } from './spine-wasm-utils';
|
||||||
|
// Import setSpineVersion through the overridden './spine-version' (= spine-version-dynamic) so it is the
|
||||||
|
// same module instance whose SPINE_VERSION live binding is read by the shared spine-define.ts.
|
||||||
|
import { setSpineVersion } from './spine-version';
|
||||||
|
|
||||||
|
function getSelectedSpineVersion (): string {
|
||||||
|
const v = (globalThis as any)._CC_SPINE_VERSION;
|
||||||
|
return v === '4.2' ? '4.2' : '3.8';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function waitForSpineWasmInstantiation (): Promise<void> {
|
||||||
|
const errorReport = (msg: any): void => { error(msg); };
|
||||||
|
// The version must be set before wasm instantiation and before spine-define patches prototypes.
|
||||||
|
const version = getSelectedSpineVersion();
|
||||||
|
setSpineVersion(version);
|
||||||
|
return ensureWasmModuleReady().then((): Promise<void> => {
|
||||||
|
//We should use static code here, import operation will cause file copy to cache folder.
|
||||||
|
if (version === '4.2') {
|
||||||
|
if (shouldUseWasmModule()) {
|
||||||
|
return Promise.all([
|
||||||
|
import('external:emscripten/spine/4.2/spine.wasm.js'),
|
||||||
|
import('external:emscripten/spine/4.2/spine.wasm'),
|
||||||
|
]).then(([
|
||||||
|
{ default: wasmFactory },
|
||||||
|
{ default: spineWasmUrl },
|
||||||
|
]) => initWasm(wasmFactory, spineWasmUrl));
|
||||||
|
} else {
|
||||||
|
return Promise.all([
|
||||||
|
import('external:emscripten/spine/4.2/spine.asm.js'),
|
||||||
|
import('external:emscripten/spine/4.2/spine.js.mem'),
|
||||||
|
]).then(([
|
||||||
|
{ default: asmFactory },
|
||||||
|
{ default: asmJsMemUrl },
|
||||||
|
]) => initAsmJS(asmFactory, asmJsMemUrl));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (shouldUseWasmModule()) {
|
||||||
|
return Promise.all([
|
||||||
|
import('external:emscripten/spine/3.8/spine.wasm.js'),
|
||||||
|
import('external:emscripten/spine/3.8/spine.wasm'),
|
||||||
|
]).then(([
|
||||||
|
{ default: wasmFactory },
|
||||||
|
{ default: spineWasmUrl },
|
||||||
|
]) => initWasm(wasmFactory, spineWasmUrl));
|
||||||
|
} else {
|
||||||
|
return Promise.all([
|
||||||
|
import('external:emscripten/spine/3.8/spine.asm.js'),
|
||||||
|
import('external:emscripten/spine/3.8/spine.js.mem'),
|
||||||
|
]).then(([
|
||||||
|
{ default: asmFactory },
|
||||||
|
{ default: asmJsMemUrl },
|
||||||
|
]) => initAsmJS(asmFactory, asmJsMemUrl));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).catch(errorReport);
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user