mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-20 23:52:40 +08:00
Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 178b9edca9 | |||
| 25026f9edd | |||
| 5bcfb9fa04 | |||
| a56706c9ad | |||
| 022be418f9 | |||
| 86fe5f41cd | |||
| a69be8d0a7 | |||
| 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 |
@@ -17,7 +17,7 @@ jobs:
|
||||
name: "Linux-Ubuntu"
|
||||
if:
|
||||
(! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration'))
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Download external libraries
|
||||
|
||||
@@ -255,7 +255,7 @@ jobs:
|
||||
name: "Openharmony"
|
||||
if:
|
||||
(! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration'))
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
# Set the type of machine to run on
|
||||
if:
|
||||
(! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration'))
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
# Checks out a copy of your repository on the ubuntu-latest machine
|
||||
|
||||
Vendored
+83
@@ -37,6 +37,38 @@ declare module 'pal/minigame' {
|
||||
getSharedCanvas(): 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
|
||||
getFileSystemManager(): FileSystemManager;
|
||||
loadSubpackage? (option: LoadSubpackageOption): LoadSubpackageTask;
|
||||
@@ -133,6 +165,57 @@ declare module 'pal/minigame' {
|
||||
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 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.
|
||||
*/
|
||||
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 {
|
||||
@@ -58,6 +64,12 @@ declare module 'pal/screen-adapter' {
|
||||
* Query the current fullscreen state.
|
||||
*/
|
||||
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 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.
|
||||
|
||||
### 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
|
||||
|
||||
The current buffer beyond the limit in ui static component, please reduce the amount
|
||||
@@ -3984,3 +3996,71 @@ 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).
|
||||
|
||||
@@ -300,6 +300,13 @@
|
||||
"overrideConstants": {
|
||||
"CULL_MESHOPT": false
|
||||
}
|
||||
},
|
||||
"worker": {
|
||||
"modules": ["worker"]
|
||||
},
|
||||
"worker-pool": {
|
||||
"modules": ["worker", "worker-pool"],
|
||||
"dependentModules": ["worker"]
|
||||
}
|
||||
},
|
||||
"moduleOverrides": [{
|
||||
@@ -383,6 +390,7 @@
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||
"pal/worker": "pal/worker/web/index.js",
|
||||
"pal/audio": "pal/audio/web/player.js",
|
||||
"pal/system-info": "pal/system-info/web/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.js",
|
||||
@@ -397,6 +405,7 @@
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||
"pal/worker": "pal/worker/native/index.js",
|
||||
"pal/audio": "pal/audio/native/player.js",
|
||||
"pal/system-info": "pal/system-info/native/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.js",
|
||||
@@ -411,6 +420,7 @@
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.js",
|
||||
"pal/worker": "pal/worker/minigame/index.js",
|
||||
"pal/audio": "pal/audio/minigame/player.js",
|
||||
"pal/system-info": "pal/system-info/minigame/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
|
||||
@@ -425,6 +435,7 @@
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/runtime.js",
|
||||
"pal/worker": "pal/worker/minigame/index.js",
|
||||
"pal/audio": "pal/audio/minigame/player.js",
|
||||
"pal/system-info": "pal/system-info/minigame/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
|
||||
@@ -439,6 +450,7 @@
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||
"pal/worker": "pal/worker/nodejs/index.js",
|
||||
"pal/audio": "pal/audio/nodejs/player.js",
|
||||
"pal/system-info": "pal/system-info/nodejs/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.js",
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
Copyright (c) 2017-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.
|
||||
*/
|
||||
|
||||
// Vertex/index capacity limits of the graphics geometry.
|
||||
|
||||
// Uint16 can address 65536 vertices (indices 0-65535), and a single fill()/stroke() batch is not
|
||||
// split, so the buffers have to cover this count.
|
||||
export const MAX_VERTEX_COUNT = 65536;
|
||||
// Fill and stroke both emit at most 3 indices per vertex, see GraphicsAssembler.
|
||||
export const INDICES_PER_VERTEX = 3;
|
||||
export const MAX_INDEX_COUNT = MAX_VERTEX_COUNT * INDICES_PER_VERTEX;
|
||||
@@ -28,12 +28,10 @@ import { MeshRenderData } from '../../../renderer/render-data';
|
||||
import { IBatcher } from '../../../renderer/i-batcher';
|
||||
import { Graphics } from '../../../components/graphics';
|
||||
import { LineCap, LineJoin, PointFlags } from '../types';
|
||||
import { MAX_VERTEX_COUNT, INDICES_PER_VERTEX } from '../constants';
|
||||
import { earcut as Earcut } from './earcut';
|
||||
import { Impl, Point } from './impl';
|
||||
|
||||
const MAX_VERTEX = 65535;
|
||||
const MAX_INDICES = MAX_VERTEX * 2;
|
||||
|
||||
const PI = Math.PI;
|
||||
const min = Math.min;
|
||||
const max = Math.max;
|
||||
@@ -95,7 +93,7 @@ export class GraphicsAssembler implements IAssembler {
|
||||
let meshBuffer = renderData;
|
||||
|
||||
const maxVertexCount = meshBuffer ? meshBuffer.vertexStart + vertexCount : 0;
|
||||
if (maxVertexCount > MAX_VERTEX || maxVertexCount * 3 > MAX_INDICES) {
|
||||
if (maxVertexCount > MAX_VERTEX_COUNT) {
|
||||
++_impl.dataOffset;
|
||||
|
||||
if (_impl.dataOffset < renderDataList.length) {
|
||||
@@ -109,7 +107,7 @@ export class GraphicsAssembler implements IAssembler {
|
||||
}
|
||||
|
||||
if (meshBuffer && meshBuffer.vertexCount < maxVertexCount) {
|
||||
meshBuffer.request(vertexCount, vertexCount * 3);
|
||||
meshBuffer.request(vertexCount, vertexCount * INDICES_PER_VERTEX);
|
||||
}
|
||||
|
||||
return renderData;
|
||||
|
||||
@@ -32,6 +32,7 @@ import { safeMeasureText, BASELINE_RATIO, MIDDLE_RATIO, getBaselineOffset, getSy
|
||||
import { director, DirectorEvent } from '../../../game/director';
|
||||
import { ccwindow } from '../../../core/global-exports';
|
||||
import { TextureBase } from '../../../asset/assets/texture-base';
|
||||
import { buildFontDesc, CssFontFamily, DEFAULT_FONT_FAMILY } from '../../utils/font-family';
|
||||
|
||||
export interface ISharedLabelData {
|
||||
canvas: HTMLCanvasElement;
|
||||
@@ -102,7 +103,7 @@ interface ILabelInfo {
|
||||
fontSize: number;
|
||||
lineHeight: number;
|
||||
hash: string;
|
||||
fontFamily: string;
|
||||
fontFamily: CssFontFamily;
|
||||
fontDesc: string;
|
||||
hAlign: number;
|
||||
vAlign: number;
|
||||
@@ -194,10 +195,7 @@ class LetterTexture {
|
||||
// Add a white background to avoid black edges.
|
||||
context.fillStyle = _backgroundStyle;
|
||||
context.fillRect(0, 0, width, height);
|
||||
context.font = labelInfo.fontDesc.replace(
|
||||
/(\d+)(\.\d+)?(px|em|rem|pt)/g,
|
||||
(w, m: string, n: string, u: string) => (+m * fontScale + (+n || 0) * fontScale).toString() + u,
|
||||
);
|
||||
context.font = buildFontDesc(labelInfo.fontSize * fontScale, labelInfo.fontFamily);
|
||||
|
||||
const fontSize = labelInfo.fontSize * fontScale;
|
||||
const startX = width / 2;
|
||||
@@ -425,7 +423,7 @@ export interface IShareLabelInfo {
|
||||
hAlign: number;
|
||||
vAlign: number;
|
||||
hash: string;
|
||||
fontFamily: string;
|
||||
fontFamily: CssFontFamily;
|
||||
fontDesc: string;
|
||||
color: Color;
|
||||
isOutlined: boolean;
|
||||
@@ -441,7 +439,7 @@ export const shareLabelInfo: IShareLabelInfo = {
|
||||
hAlign: 0,
|
||||
vAlign: 0,
|
||||
hash: '',
|
||||
fontFamily: '',
|
||||
fontFamily: DEFAULT_FONT_FAMILY,
|
||||
fontDesc: 'Arial',
|
||||
color: Color.WHITE.clone(),
|
||||
isOutlined: false,
|
||||
|
||||
@@ -26,6 +26,7 @@ import type { Label } from '../../components';
|
||||
import { IAssembler } from '../../renderer/base';
|
||||
import { BmfontUtils } from './bmfontUtils';
|
||||
import { shareLabelInfo, LetterAtlas, computeHash, LetterRenderTexture } from './font-utils';
|
||||
import { buildFontDesc, CssFontFamily, getCanvasFontFamily } from '../../utils/font-family';
|
||||
|
||||
const _atlasWidth = 1024;
|
||||
const _atlasHeight = 1024;
|
||||
@@ -59,17 +60,8 @@ export class LetterFont extends BmfontUtils {
|
||||
}
|
||||
}
|
||||
|
||||
protected _getFontFamily (comp: Label): string {
|
||||
let fontFamily = 'Arial';
|
||||
if (!comp.useSystemFont) {
|
||||
if (comp.font) {
|
||||
fontFamily = comp.font._nativeAsset || 'Arial';
|
||||
}
|
||||
} else {
|
||||
fontFamily = comp.fontFamily || 'Arial';
|
||||
}
|
||||
|
||||
return fontFamily;
|
||||
protected _getFontFamily (comp: Label): CssFontFamily {
|
||||
return getCanvasFontFamily(comp);
|
||||
}
|
||||
|
||||
protected _updateLabelInfo (comp: Label): void {
|
||||
@@ -79,12 +71,6 @@ export class LetterFont extends BmfontUtils {
|
||||
}
|
||||
|
||||
protected _getFontDesc (): string {
|
||||
let fontDesc = `${shareLabelInfo.fontSize.toString()}px `;
|
||||
fontDesc += shareLabelInfo.fontFamily;
|
||||
if (_isBold) {
|
||||
fontDesc = `bold ${fontDesc}`;
|
||||
}
|
||||
|
||||
return fontDesc;
|
||||
return buildFontDesc(shareLabelInfo.fontSize, shareLabelInfo.fontFamily, _isBold);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
safeMeasureText,
|
||||
} from '../../utils/text-utils';
|
||||
import type { Batcher2D } from '../../renderer/batcher-2d';
|
||||
import { buildFontDesc, CssFontFamily } from '../../utils/font-family';
|
||||
|
||||
const Alignment = [
|
||||
'left', // macro.TextAlignment.LEFT
|
||||
@@ -115,7 +116,7 @@ export class TextProcessing {
|
||||
const maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
|
||||
const canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
|
||||
this._fontScale *= canvasScaleToMaxSizeRatio;
|
||||
this._fontScale = Math.max(1, this._fontScale);
|
||||
this._fontScale = Math.max(0.1, this._fontScale);
|
||||
}
|
||||
|
||||
this._updatePaddingRect(style, outputLayoutData);
|
||||
@@ -260,18 +261,8 @@ export class TextProcessing {
|
||||
}
|
||||
|
||||
// can cache
|
||||
private _getFontDesc (fontSize: number, fontFamily: string, isBold: boolean, isItalic: boolean): string {
|
||||
let fontDesc = `${fontSize.toString()}px `;
|
||||
fontDesc += fontFamily;
|
||||
if (isBold) {
|
||||
fontDesc = `bold ${fontDesc}`;
|
||||
}
|
||||
|
||||
if (isItalic) {
|
||||
fontDesc = `italic ${fontDesc}`;
|
||||
}
|
||||
|
||||
return fontDesc;
|
||||
private _getFontDesc (fontSize: number, fontFamily: CssFontFamily, isBold: boolean, isItalic: boolean): string {
|
||||
return buildFontDesc(fontSize, fontFamily, isBold, isItalic);
|
||||
}
|
||||
|
||||
// can cache
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
import { Color } from '../../../core';
|
||||
import { IConfig } from '../../assets/bitmap-font';
|
||||
import { SpriteFrame } from '../../assets/sprite-frame';
|
||||
import { CssFontFamily, DEFAULT_FONT_FAMILY } from '../../utils/font-family';
|
||||
|
||||
export class TextStyle {
|
||||
// ---------------ttf extra part-----------------
|
||||
@@ -59,7 +60,7 @@ export class TextStyle {
|
||||
public bmfontScale = 1.0;// both
|
||||
|
||||
// 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
|
||||
|
||||
// -----------------------bitMap extra part-------------------------
|
||||
|
||||
@@ -31,6 +31,7 @@ import type { TextStyle } from './text-style';
|
||||
import type { TextLayout } from './text-layout';
|
||||
import { view } from '../../../ui/view';
|
||||
import { approx } from '../../../core';
|
||||
import { CssFontFamily, getCanvasFontFamily } from '../../utils/font-family';
|
||||
|
||||
const Overflow = Label.Overflow;
|
||||
|
||||
@@ -192,18 +193,8 @@ export class TTFUtils {
|
||||
// no needs to update uv data
|
||||
}
|
||||
|
||||
_updateFontFamily (comp: Label): string {
|
||||
let _fontFamily = '';
|
||||
if (!comp.useSystemFont) {
|
||||
if (comp.font) {
|
||||
_fontFamily = comp.font._nativeAsset || 'Arial';
|
||||
} else {
|
||||
_fontFamily = 'Arial';
|
||||
}
|
||||
} else {
|
||||
_fontFamily = comp.fontFamily || 'Arial';
|
||||
}
|
||||
return _fontFamily;
|
||||
_updateFontFamily (comp: Label): CssFontFamily {
|
||||
return getCanvasFontFamily(comp);
|
||||
}
|
||||
|
||||
_calDynamicAtlas (comp: Label, outputLayoutData: TextOutputLayoutData): void {
|
||||
|
||||
@@ -32,6 +32,7 @@ import { Color, warnID, cclegacy } from '../../core';
|
||||
import { scene } from '../../render-scene';
|
||||
import type { IBatcher } from '../renderer/i-batcher';
|
||||
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 { Material, RenderingSubMesh } from '../../asset/assets';
|
||||
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 { RenderEntity, RenderEntityType } from '../renderer/render-entity';
|
||||
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([
|
||||
new Attribute('a_dist', Format.R32F),
|
||||
@@ -48,6 +51,15 @@ const componentPerVertex = getComponentPerVertex(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
|
||||
* Graphics component.
|
||||
@@ -635,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.
|
||||
*/
|
||||
public activeSubModel (idx: number): void {
|
||||
public activeSubModel (idx: number, vertexCount = 1, indexCount = 1): void {
|
||||
if (!this.model) {
|
||||
warnID(4500, this.node.name);
|
||||
return;
|
||||
@@ -646,13 +658,13 @@ export class Graphics extends UIRenderer {
|
||||
const vertexBuffer = gfxDevice.createBuffer(new BufferInfo(
|
||||
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
|
||||
MemoryUsageBit.DEVICE,
|
||||
65536 * stride, // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
growCapacity(vertexCount, 0, MAX_VERTEX_COUNT) * stride,
|
||||
stride,
|
||||
));
|
||||
const indexBuffer = gfxDevice.createBuffer(new BufferInfo(
|
||||
BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST,
|
||||
MemoryUsageBit.DEVICE,
|
||||
65536 * Uint16Array.BYTES_PER_ELEMENT * 2, // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
growCapacity(indexCount, 0, MAX_INDEX_COUNT) * Uint16Array.BYTES_PER_ELEMENT,
|
||||
Uint16Array.BYTES_PER_ELEMENT,
|
||||
));
|
||||
|
||||
@@ -683,6 +695,9 @@ export class Graphics extends UIRenderer {
|
||||
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);
|
||||
ia.vertexBuffers[0].update(vb);
|
||||
ia.vertexCount = renderData.vertexStart;
|
||||
@@ -696,6 +711,27 @@ export class Graphics extends UIRenderer {
|
||||
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 {
|
||||
if (this._isNeedUploadData) {
|
||||
if (this.impl) {
|
||||
@@ -703,7 +739,8 @@ export class Graphics extends UIRenderer {
|
||||
const len = this.model!.subModels.length;
|
||||
if (renderDataList.length > len) {
|
||||
for (let i = len; i < renderDataList.length; i++) {
|
||||
this.activeSubModel(i);
|
||||
const renderData = renderDataList[i];
|
||||
this.activeSubModel(i, renderData.vertexStart, renderData.indexStart);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,24 +395,59 @@ export class MeshBuffer {
|
||||
}
|
||||
const byteCount = this.byteOffset;
|
||||
const indexCount = this.indexOffset;
|
||||
const indexBytes = indexCount * 2;
|
||||
let allUploaded = true;
|
||||
for (let i = 0; i < submitCount; ++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);
|
||||
|
||||
let requiredVertexBytes = byteCount;
|
||||
const vertexBuffer = iaRef.vertexBuffers[0];
|
||||
if (byteCount > vertexBuffer.size) {
|
||||
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) {
|
||||
iaRef.indexBuffer.resize(indexCount * 2);
|
||||
const indexBuffer = iaRef.indexBuffer;
|
||||
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 {
|
||||
|
||||
@@ -735,6 +735,10 @@ export class MeshRenderData extends BaseRenderData {
|
||||
this._vertexBuffers[0].destroy();
|
||||
this._vertexBuffers = [];
|
||||
}
|
||||
if (this._indexBuffer) {
|
||||
this._indexBuffer.destroy();
|
||||
this._indexBuffer = null!;
|
||||
}
|
||||
this._iaInfo = null!;
|
||||
this.vData = new Float32Array(256 * this.stride);
|
||||
this.iData = new Uint16Array(256 * 6);
|
||||
|
||||
@@ -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 { safeMeasureText } from './text-utils';
|
||||
import { buildFontDesc, quoteFontFamily } from './font-family';
|
||||
import downloader from '../../asset/asset-manager/downloader';
|
||||
import factory from '../../asset/asset-manager/factory';
|
||||
import { TTFFont } from '../assets/ttf-font';
|
||||
@@ -31,10 +31,13 @@ import { ccwindow } from '../../core/global-exports';
|
||||
|
||||
const ccdocument = ccwindow.document;
|
||||
|
||||
type FontCallback = (err: Error | null, family?: string) => void;
|
||||
|
||||
interface IFontLoadHandle {
|
||||
fontFamilyName: string;
|
||||
fontDesc: string;
|
||||
refWidth: number;
|
||||
onComplete: ((err: Error | null, data?: any | null) => void);
|
||||
onComplete: FontCallback;
|
||||
startTime: number;
|
||||
}
|
||||
|
||||
@@ -90,9 +93,9 @@ function checkFontLoaded (): void {
|
||||
}
|
||||
|
||||
const oldWidth = fontLoadHandle.refWidth;
|
||||
const fontDesc = `40px ${fontFamily}`;
|
||||
_canvasContext!.font = fontDesc;
|
||||
const newWidth = safeMeasureText(_canvasContext!, _testString, fontDesc);
|
||||
_canvasContext!.font = fontLoadHandle.fontDesc;
|
||||
// Font availability changes while loading; do not cache fallback-font metrics.
|
||||
const newWidth = _canvasContext!.measureText(_testString).width;
|
||||
// loaded successfully
|
||||
if (oldWidth !== newWidth) {
|
||||
_loadingFonts.splice(i, 1);
|
||||
@@ -109,7 +112,7 @@ function checkFontLoaded (): void {
|
||||
}
|
||||
|
||||
// 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 check = (): void => {
|
||||
const now = Date.now();
|
||||
@@ -117,7 +120,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: ((err: Er
|
||||
if (now - start >= _timeout) {
|
||||
reject();
|
||||
} else {
|
||||
(ccdocument as any).fonts.load(`40px ${font}`).then((fonts) => {
|
||||
(ccdocument as any).fonts.load(fontDesc).then((fonts) => {
|
||||
if (fonts.length >= 1) {
|
||||
resolve();
|
||||
} 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);
|
||||
// Already loaded fonts
|
||||
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
|
||||
const fontDesc = `40px ${fontFamilyName}`;
|
||||
const familyCss = quoteFontFamily(fontFamilyName);
|
||||
const fontDesc = buildFontDesc(40, familyCss);
|
||||
|
||||
// Setup font face style
|
||||
const fontStyle = ccdocument.createElement('style');
|
||||
fontStyle.type = 'text/css';
|
||||
let fontStr = '';
|
||||
if (Number.isNaN(fontFamilyName)) {
|
||||
fontStr += `@font-face { font-family:${fontFamilyName}; src:`;
|
||||
} else {
|
||||
fontStr += `@font-face { font-family:"${fontFamilyName}"; src:`;
|
||||
}
|
||||
let fontStr = `@font-face { font-family:${familyCss}; src:`;
|
||||
fontStr += `url("${url}");`;
|
||||
fontStyle.textContent = `${fontStr}}`;
|
||||
ccdocument.body.appendChild(fontStyle);
|
||||
@@ -184,7 +183,7 @@ export function loadFont (url: string, options: Record<string, any>, onComplete:
|
||||
// Preload font with div
|
||||
const preloadDiv = ccdocument.createElement('div');
|
||||
const divStyle = preloadDiv.style;
|
||||
divStyle.fontFamily = fontFamilyName;
|
||||
divStyle.fontFamily = familyCss;
|
||||
preloadDiv.innerHTML = '.';
|
||||
divStyle.position = 'absolute';
|
||||
divStyle.left = '-100px';
|
||||
@@ -192,12 +191,14 @@ export function loadFont (url: string, options: Record<string, any>, onComplete:
|
||||
ccdocument.body.appendChild(preloadDiv);
|
||||
|
||||
if (useNativeCheck()) {
|
||||
nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete);
|
||||
nativeCheckFontLoaded(Date.now(), fontFamilyName, fontDesc, onComplete);
|
||||
} else {
|
||||
const refWidth = safeMeasureText(_canvasContext!, _testString, fontDesc);
|
||||
_canvasContext!.font = fontDesc;
|
||||
const refWidth = _canvasContext!.measureText(_testString).width;
|
||||
// Save loading font
|
||||
const fontLoadHandle = {
|
||||
fontFamilyName,
|
||||
fontDesc,
|
||||
refWidth,
|
||||
onComplete,
|
||||
startTime: Date.now(),
|
||||
@@ -221,9 +222,6 @@ export function getFontFamily (fontHandle: string): string {
|
||||
} else {
|
||||
fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`;
|
||||
}
|
||||
if (fontFamilyName.indexOf(' ') !== -1) {
|
||||
fontFamilyName = `"${fontFamilyName}"`;
|
||||
}
|
||||
return fontFamilyName;
|
||||
}
|
||||
|
||||
|
||||
@@ -172,13 +172,18 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
|
||||
// Fill index buffer.
|
||||
let indexBuffer: ArrayBuffer | null = null;
|
||||
let idxCount = 0;
|
||||
const idxStride = 2;
|
||||
let idxStride = 2;
|
||||
let indexFormat = Format.R16UI;
|
||||
if (geometry.indices) {
|
||||
const { indices } = geometry;
|
||||
idxCount = indices.length;
|
||||
if (indices.some((i) => i > 0xFFFF)) {
|
||||
idxStride = 4;
|
||||
indexFormat = Format.R32UI;
|
||||
}
|
||||
indexBuffer = new ArrayBuffer(idxStride * idxCount);
|
||||
const indexBufferView = new DataView(indexBuffer);
|
||||
writeBuffer(indexBufferView, indices, Format.R16UI);
|
||||
writeBuffer(indexBufferView, indices, indexFormat);
|
||||
}
|
||||
|
||||
// Create primitive.
|
||||
|
||||
@@ -106,6 +106,13 @@ export class BakedSkinningModel extends MorphModel {
|
||||
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
|
||||
|
||||
@@ -142,6 +142,7 @@ export class SkinningModel extends MorphModel {
|
||||
}
|
||||
this._bufferIndices = null; this._joints.length = 0;
|
||||
if (!skeleton || !skinningRoot || !mesh) { return; }
|
||||
const prevRealTimeTextureMode = this._realTimeTextureMode;
|
||||
this._realTimeTextureMode = false;
|
||||
if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) { this._realTimeTextureMode = true; }
|
||||
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); }
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -177,21 +177,21 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer {
|
||||
@override
|
||||
@visible(false)
|
||||
get mesh (): Mesh | null {
|
||||
return super.mesh;
|
||||
return Reflect.get(SkinnedMeshRenderer.prototype, 'mesh', this);
|
||||
}
|
||||
|
||||
set mesh (val) {
|
||||
super.mesh = val;
|
||||
Reflect.set(SkinnedMeshRenderer.prototype, 'mesh', val, this);
|
||||
}
|
||||
|
||||
@override
|
||||
@visible(false)
|
||||
get skeleton (): Skeleton | null {
|
||||
return super.skeleton;
|
||||
return Reflect.get(SkinnedMeshRenderer.prototype, 'skeleton', this);
|
||||
}
|
||||
|
||||
set skeleton (val) {
|
||||
super.skeleton = val;
|
||||
Reflect.set(SkinnedMeshRenderer.prototype, 'skeleton', val, this);
|
||||
}
|
||||
|
||||
public onLoad (): void {
|
||||
|
||||
@@ -53,6 +53,19 @@ const _windowInfo: IRenderWindowInfo = {
|
||||
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,
|
||||
* 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.
|
||||
* @zh 修改渲染贴图的尺寸。
|
||||
* @param width @en The pixel width to resize to, the range is from 1 to 2048. @zh 需要调整到的像素宽度,范围为 1-2048。
|
||||
* @param height @en The pixel height 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.
|
||||
* @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 {
|
||||
this._width = Math.floor(clamp(width, 1, 2048));
|
||||
this._height = Math.floor(clamp(height, 1, 2048));
|
||||
const maxSize = getMaxRenderTextureSize() ?? FALLBACK_MAX_RENDER_TEXTURE_SIZE;
|
||||
this._width = Math.floor(clamp(width, 1, maxSize));
|
||||
this._height = Math.floor(clamp(height, 1, maxSize));
|
||||
if (this._window) {
|
||||
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.
|
||||
*/
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -45,5 +45,5 @@ export {
|
||||
DebugMode,
|
||||
} from './debug';
|
||||
|
||||
export { screen } from './screen';
|
||||
export { screen, MaxDPR } from './screen';
|
||||
export type { Screen } from './screen';
|
||||
|
||||
@@ -25,12 +25,34 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { screenAdapter, IScreenOptions } from 'pal/screen-adapter';
|
||||
import { legacyCC } from '../global-exports';
|
||||
import { Size } from '../math';
|
||||
import { settings, SettingsCategory } from '../settings';
|
||||
import { error, warn, warnID } from './debug';
|
||||
import { PalScreenEvent } from '../../../pal/screen-adapter/enum-type';
|
||||
import { error, getError, warn, warnID } from './debug';
|
||||
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.
|
||||
* @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。
|
||||
@@ -40,10 +62,18 @@ export class Screen {
|
||||
* @internal
|
||||
*/
|
||||
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 orientation = settings.querySettings(SettingsCategory.SCREEN, 'orientation') ?? 'auto';
|
||||
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;
|
||||
if (!director.root?.pipeline) {
|
||||
warnID(1220);
|
||||
@@ -51,6 +81,13 @@ export class Screen {
|
||||
}
|
||||
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}
|
||||
* @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.
|
||||
* Many browsers forbid to enter full screen mode without an user intended interaction.
|
||||
@@ -150,7 +191,11 @@ export class Screen {
|
||||
* @return {Promise}
|
||||
*/
|
||||
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) {
|
||||
warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise');
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ export class EmptyBuffer extends Buffer {
|
||||
}
|
||||
}
|
||||
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 {}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
} from './webgl-commands';
|
||||
import { IWebGLGPUBuffer, IWebGLGPUBufferView, WebGLIndirectDrawInfos } from './webgl-gpu-objects';
|
||||
import { WebGLDeviceManager } from './webgl-define';
|
||||
import { warnID } from '../../core/platform/debug';
|
||||
import { warn, warnID } from '../../core/platform/debug';
|
||||
|
||||
/** @mangle */
|
||||
export class WebGLBuffer extends Buffer {
|
||||
@@ -48,6 +48,7 @@ export class WebGLBuffer extends Buffer {
|
||||
private _gpuBuffer: IWebGLGPUBuffer | null = null;
|
||||
private _gpuBufferView: IWebGLGPUBufferView | null = null;
|
||||
private _uniformBuffer: Uint8Array | null = null;
|
||||
private _lastFailedSize = 0;
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
@@ -125,9 +126,6 @@ export class WebGLBuffer extends Buffer {
|
||||
const oldSize = this._size;
|
||||
if (oldSize === size) { return; }
|
||||
|
||||
this._size = size;
|
||||
this._count = this._size / this._stride;
|
||||
|
||||
if (this._uniformBuffer) {
|
||||
this._uniformBuffer = new Uint8Array(size);
|
||||
}
|
||||
@@ -140,8 +138,18 @@ export class WebGLBuffer extends Buffer {
|
||||
this._gpuBuffer.size = size;
|
||||
if (size > 0) {
|
||||
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 {
|
||||
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);
|
||||
stateCache.glArrayBuffer = null;
|
||||
} else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
|
||||
@@ -594,6 +596,8 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL
|
||||
} else {
|
||||
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);
|
||||
stateCache.glElementArrayBuffer = null;
|
||||
} else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
|
||||
@@ -630,6 +634,7 @@ export function WebGLCmdFuncUpdateBuffer (
|
||||
gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
|
||||
}
|
||||
} else {
|
||||
if (size > gpuBuffer.size) { return; }
|
||||
const buff = buffer as ArrayBuffer;
|
||||
const { gl, stateCache } = device;
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { warnID } from '../../core/platform/debug';
|
||||
import { warn, warnID } from '../../core/platform/debug';
|
||||
import { Buffer } from '../base/buffer';
|
||||
import { BufferUsageBit, BufferSource, BufferInfo, BufferViewInfo } from '../base/define';
|
||||
import {
|
||||
@@ -45,6 +45,7 @@ export class WebGL2Buffer extends Buffer {
|
||||
}
|
||||
|
||||
private _gpuBuffer: IWebGL2GPUBuffer | null = null;
|
||||
private _lastFailedSize = 0;
|
||||
|
||||
public initialize (info: Readonly<BufferInfo> | Readonly<BufferViewInfo>): void {
|
||||
if ('buffer' in info) { // buffer view
|
||||
@@ -114,15 +115,22 @@ export class WebGL2Buffer extends Buffer {
|
||||
const oldSize = this._size;
|
||||
if (oldSize === size) { return; }
|
||||
|
||||
this._size = size;
|
||||
this._count = this._size / this._stride;
|
||||
|
||||
if (this._gpuBuffer) {
|
||||
this._gpuBuffer.size = size;
|
||||
if (size > 0) {
|
||||
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 {
|
||||
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);
|
||||
cache.glArrayBuffer = null;
|
||||
} else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
|
||||
@@ -790,6 +792,8 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb
|
||||
} else {
|
||||
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);
|
||||
cache.glElementArrayBuffer = null;
|
||||
} 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);
|
||||
gpuBuffer.size = gl.getBufferParameter(WebGLConstants.UNIFORM_BUFFER, WebGLConstants.BUFFER_SIZE) as number;
|
||||
|
||||
gl.bindBuffer(WebGLConstants.UNIFORM_BUFFER, null);
|
||||
cache.glUniformBuffer = null;
|
||||
} else if ((gpuBuffer.usage & BufferUsageBit.INDIRECT)
|
||||
@@ -824,6 +830,7 @@ export function WebGL2CmdFuncUpdateBuffer (
|
||||
gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
|
||||
}
|
||||
} else {
|
||||
if (size > gpuBuffer.size) { return; }
|
||||
const buff = buffer as ArrayBuffer;
|
||||
const { gl } = device;
|
||||
const cache = device.getStateCache();
|
||||
|
||||
+13
-5
@@ -24,7 +24,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR_NOT_IN_PREVIEW, HTML5, NATIVE } from 'internal:constants';
|
||||
import { EDITOR_NOT_IN_PREVIEW, HTML5, NATIVE, WECHAT } from 'internal:constants';
|
||||
import { AccelerometerInputSource, GamepadInputDevice, HMDInputDevice, HandheldInputDevice,
|
||||
HandleInputDevice, KeyboardInputSource, MouseInputSource, TouchInputSource } from 'pal/input';
|
||||
import { touchManager } from '../../pal/input/touch-manager';
|
||||
@@ -380,9 +380,15 @@ export class Input {
|
||||
}
|
||||
|
||||
if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) {
|
||||
// Game View still needs mouse-to-touch simulation even when INPUT_TOUCH is true.
|
||||
// WeChat PC already maps left mouse clicks to touch events.
|
||||
// https://developers.weixin.qq.com/minigame/dev/guide/open-ability/pc-game.html
|
||||
const shouldSimulateTouch = !(WECHAT && sys.hasFeature(sys.Feature.INPUT_TOUCH));
|
||||
mouseInput.on(InputEventType.MOUSE_DOWN, (event): void => {
|
||||
self._needSimulateTouchMoveEvent = true;
|
||||
self._simulateEventTouch(event);
|
||||
if (shouldSimulateTouch) {
|
||||
self._needSimulateTouchMoveEvent = true;
|
||||
self._simulateEventTouch(event);
|
||||
}
|
||||
self._dispatchEventMouse(event);
|
||||
});
|
||||
mouseInput.on(InputEventType.MOUSE_MOVE, (event): void => {
|
||||
@@ -392,8 +398,10 @@ export class Input {
|
||||
self._dispatchEventMouse(event);
|
||||
});
|
||||
mouseInput.on(InputEventType.MOUSE_UP, (event): void => {
|
||||
self._needSimulateTouchMoveEvent = false;
|
||||
self._simulateEventTouch(event);
|
||||
if (shouldSimulateTouch) {
|
||||
self._needSimulateTouchMoveEvent = false;
|
||||
self._simulateEventTouch(event);
|
||||
}
|
||||
self._dispatchEventMouse(event);
|
||||
});
|
||||
mouseInput.on(InputEventType.MOUSE_WHEEL, (event): void => {
|
||||
|
||||
@@ -24,6 +24,12 @@
|
||||
|
||||
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 { ModelRenderer } from './model-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);
|
||||
}
|
||||
@@ -110,7 +110,7 @@ export default class ShapeModule {
|
||||
*/
|
||||
@displayOrder(6)
|
||||
@tooltip('i18n:shapeModule.arc')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectArc (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Cone', 'Circle'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -131,7 +131,7 @@ export default class ShapeModule {
|
||||
*/
|
||||
@displayOrder(5)
|
||||
@tooltip('i18n:shapeModule.angle')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectAngle (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Cone'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -208,7 +208,7 @@ export default class ShapeModule {
|
||||
@serializable
|
||||
@displayOrder(2)
|
||||
@tooltip('i18n:shapeModule.emitFrom')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectEmitFrom (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Box', 'Cone', 'Sphere', 'Hemisphere'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -216,8 +216,8 @@ export default class ShapeModule {
|
||||
public emitFrom = ParticleEmitLocation.Volume;
|
||||
|
||||
/**
|
||||
* @en Align particle with particle direction.
|
||||
* @zh 根据粒子的初始方向决定粒子的移动方向。
|
||||
* @en Align the particle's negative Z axis with its initial emission direction, then apply start rotation.
|
||||
* @zh 将粒子的负 Z 轴对齐到初始发射方向,再叠加初始旋转。
|
||||
*/
|
||||
@serializable
|
||||
@displayOrder(16)
|
||||
@@ -258,7 +258,7 @@ export default class ShapeModule {
|
||||
@serializable
|
||||
@displayOrder(3)
|
||||
@tooltip('i18n:shapeModule.radius')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectRadius (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Circle', 'Cone', 'Sphere', 'Hemisphere'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -278,7 +278,7 @@ export default class ShapeModule {
|
||||
@serializable
|
||||
@displayOrder(4)
|
||||
@tooltip('i18n:shapeModule.radiusThickness')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectRadiusThickness (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Circle', 'Cone', 'Sphere', 'Hemisphere'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -293,7 +293,7 @@ export default class ShapeModule {
|
||||
@serializable
|
||||
@displayOrder(7)
|
||||
@tooltip('i18n:shapeModule.arcMode')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectArcMode (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Cone', 'Circle'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -304,11 +304,12 @@ export default class ShapeModule {
|
||||
* @en Control arc spread for Cone and circle shape.
|
||||
* @zh 控制可能产生粒子的弧周围的离散间隔。
|
||||
*/
|
||||
@visible(function noArc (this: ShapeModule) { return this.arcMode !== ParticleArcMode.Random; }) // Bug fix: Hide this input when arcMode is random
|
||||
// Bug fix: Hide this input when arcMode is random
|
||||
@visible(function noArc (this: ShapeModule) { return this.arcMode !== ParticleArcMode.Random; })
|
||||
@serializable
|
||||
@displayOrder(9)
|
||||
@tooltip('i18n:shapeModule.arcSpread')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectArcSpread (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Cone', 'Circle'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -319,13 +320,14 @@ export default class ShapeModule {
|
||||
* @en Emit speed around arc (available for Cone and Circle).
|
||||
* @zh 粒子沿圆周发射的速度。
|
||||
*/
|
||||
// Bug fix: Hide this input when arcMode is random
|
||||
@type(CurveRange)
|
||||
@visible(function noArc (this: ShapeModule) { return this.arcMode !== ParticleArcMode.Random; }) // Bug fix: Hide this input when arcMode is random
|
||||
@visible(function noArc (this: ShapeModule) { return this.arcMode !== ParticleArcMode.Random; })
|
||||
@range([0, 1])
|
||||
@serializable
|
||||
@displayOrder(10)
|
||||
@tooltip('i18n:shapeModule.arcSpeed')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectArcSpeed (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Cone', 'Circle'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -340,7 +342,7 @@ export default class ShapeModule {
|
||||
@serializable
|
||||
@displayOrder(11)
|
||||
@tooltip('i18n:shapeModule.length')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectCone (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Cone'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -354,7 +356,7 @@ export default class ShapeModule {
|
||||
@serializable
|
||||
@displayOrder(12)
|
||||
@tooltip('i18n:shapeModule.boxThickness')
|
||||
@visible(function (this: ShapeModule) {
|
||||
@visible(function selectBox (this: ShapeModule) {
|
||||
const subset: Array<keyof typeof ParticleShapeType> = ['Box'];
|
||||
const enumName = getShapeTypeEnumName(this.shapeType);
|
||||
return subset.includes(enumName);
|
||||
@@ -445,6 +447,7 @@ export default class ShapeModule {
|
||||
if (this.arcMode === ParticleArcMode.Random) {
|
||||
return randomRange(0, this._arc);
|
||||
}
|
||||
/* eslint-disable-next-line max-len */
|
||||
let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem!.time, 1)! * (this.particleSystem!.time - this.lastTime);
|
||||
this.totalAngle = angle;
|
||||
if (this.arcSpread !== 0) {
|
||||
|
||||
+14
-4
@@ -29,7 +29,8 @@ import { Vec2, Vec3 } from '../core/math';
|
||||
* @zh 此类生成噪声纹理。
|
||||
*/
|
||||
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,
|
||||
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,
|
||||
@@ -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,
|
||||
];
|
||||
|
||||
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[]) {
|
||||
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 返回生成的噪声纹理值。
|
||||
*/
|
||||
public noise (x: number, y: number, z: number, min = 0, max = 1): number {
|
||||
const p: number[] = new Array(512);
|
||||
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = this.permutation[i]; }
|
||||
const p: Uint8Array = this.permutation512;
|
||||
|
||||
const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT
|
||||
const Y = Math.floor(y) & 255; // CONTAINS POINT.
|
||||
|
||||
@@ -42,7 +42,7 @@ import VelocityOvertimeModule from './animator/velocity-overtime';
|
||||
import Burst from './burst';
|
||||
import ShapeModule from './emitter/shape-module';
|
||||
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 TrailModule from './renderer/trail';
|
||||
import { ParticleSystemRendererBase } from './renderer/particle-system-renderer-base';
|
||||
@@ -55,6 +55,9 @@ import { director, DirectorEvent } from '../game/director';
|
||||
|
||||
const _world_mat = new Mat4();
|
||||
const _world_rol = new Quat();
|
||||
const _emitDirection = new Vec3();
|
||||
const _alignRotation = new Quat();
|
||||
const _startRotation = new Quat();
|
||||
|
||||
const superMaterials = Object.getOwnPropertyDescriptor(Renderer.prototype, 'sharedMaterials')!;
|
||||
|
||||
@@ -141,7 +144,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@range([0, Number.POSITIVE_INFINITY])
|
||||
@displayOrder(10)
|
||||
@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();
|
||||
|
||||
/**
|
||||
@@ -153,7 +156,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@range([0, Number.POSITIVE_INFINITY])
|
||||
@displayOrder(10)
|
||||
@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();
|
||||
|
||||
/**
|
||||
@@ -184,7 +187,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@radian
|
||||
@displayOrder(12)
|
||||
@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();
|
||||
|
||||
/**
|
||||
@@ -196,7 +199,7 @@ export class ParticleSystem extends ModelRenderer {
|
||||
@radian
|
||||
@displayOrder(12)
|
||||
@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();
|
||||
|
||||
/**
|
||||
@@ -1376,6 +1379,14 @@ export class ParticleSystem extends ModelRenderer {
|
||||
self._textureAnimationModule.init(particle);
|
||||
}
|
||||
|
||||
const alignToDirection = self._shapeModule?.enable && self._shapeModule.alignToDirection;
|
||||
if (alignToDirection) {
|
||||
Vec3.copy(_emitDirection, particle.velocity);
|
||||
if (self._simulationSpace === ParticleSpace.World) {
|
||||
Vec3.transformQuat(_emitDirection, _emitDirection, _world_rol);
|
||||
}
|
||||
}
|
||||
|
||||
const curveStartSpeed = self.startSpeed.evaluate(loopDelta, rand)!;
|
||||
Vec3.multiplyScalar(particle.velocity, particle.velocity, curveStartSpeed);
|
||||
|
||||
@@ -1392,6 +1403,17 @@ export class ParticleSystem extends ModelRenderer {
|
||||
} else {
|
||||
particle.startEuler.set(0, 0, self.startRotationZ.evaluate(loopDelta, rand));
|
||||
}
|
||||
if (alignToDirection && _emitDirection.lengthSqr() > 0) {
|
||||
// Align before applying start rotation, in simulation space. Use the
|
||||
// shape direction so zero start speed still has a defined orientation.
|
||||
Vec3.normalize(_emitDirection, _emitDirection);
|
||||
Quat.rotationTo(_alignRotation, particleEmitZAxis, _emitDirection);
|
||||
const r2d = 180 / Math.PI;
|
||||
Quat.fromEuler(_startRotation, particle.startEuler.x * r2d, particle.startEuler.y * r2d, particle.startEuler.z * r2d);
|
||||
Quat.multiply(_startRotation, _alignRotation, _startRotation);
|
||||
Quat.toEuler(particle.startEuler, _startRotation);
|
||||
particle.startEuler.multiplyScalar(1 / r2d);
|
||||
}
|
||||
particle.rotation.set(particle.startEuler);
|
||||
|
||||
// apply startSize.
|
||||
@@ -1455,16 +1477,18 @@ export class ParticleSystem extends ModelRenderer {
|
||||
|
||||
if (!self._isEmitting) return;
|
||||
|
||||
const randTime = isCurveTwoValues(self.rateOverTime) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
|
||||
// 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) {
|
||||
const emitNum = Math.floor(self._emitRateTimeCounter);
|
||||
self._emitRateTimeCounter -= emitNum;
|
||||
self.emit(emitNum, dt);
|
||||
}
|
||||
|
||||
const randDist = isCurveTwoValues(self.rateOverDistance) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
|
||||
// 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) {
|
||||
Vec3.copy(self._oldWPos, self._curWPos);
|
||||
self.node.getWorldPosition(self._curWPos);
|
||||
|
||||
@@ -336,7 +336,16 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._alignSpace === ParticleAlignmentSpace.Local) {
|
||||
const ps = this._particleSystem;
|
||||
if (mode === ParticleRenderMode.Mesh && ps?._shapeModule?.enable && ps._shapeModule.alignToDirection) {
|
||||
// Aligned particle rotations are already in simulation space. The mesh
|
||||
// shader only needs the remaining simulation-to-world rotation.
|
||||
if (ps.simulationSpace === ParticleSpace.Local) {
|
||||
ps.node.getWorldRotation(_node_rot);
|
||||
} else {
|
||||
_node_rot.set(0, 0, 0, 1);
|
||||
}
|
||||
} else if (this._alignSpace === ParticleAlignmentSpace.Local) {
|
||||
this._particleSystem?.node.getRotation(_node_rot);
|
||||
} else if (this._alignSpace === ParticleAlignmentSpace.World) {
|
||||
this._particleSystem?.node.getWorldRotation(_node_rot);
|
||||
|
||||
@@ -265,7 +265,16 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._alignSpace === ParticleAlignmentSpace.Local) {
|
||||
const ps = this._particleSystem;
|
||||
if (mode === ParticleRenderMode.Mesh && ps?._shapeModule?.enable && ps._shapeModule.alignToDirection) {
|
||||
// Aligned particle rotations are already in simulation space. The mesh
|
||||
// shader only needs the remaining simulation-to-world rotation.
|
||||
if (ps.simulationSpace === ParticleSpace.Local) {
|
||||
ps.node.getWorldRotation(_node_rot);
|
||||
} else {
|
||||
_node_rot.set(0, 0, 0, 1);
|
||||
}
|
||||
} else if (this._alignSpace === ParticleAlignmentSpace.Local) {
|
||||
this._particleSystem?.node.getRotation(_node_rot);
|
||||
} else if (this._alignSpace === ParticleAlignmentSpace.World) {
|
||||
this._particleSystem?.node.getWorldRotation(_node_rot);
|
||||
|
||||
@@ -1264,15 +1264,6 @@ export class WebProgramLibrary implements ProgramLibrary {
|
||||
if (passSet) {
|
||||
info.setLayouts.push(passSet);
|
||||
}
|
||||
const phaseSet = getDescriptorSetLayout(
|
||||
this.layoutGraph,
|
||||
subpassOrPassID,
|
||||
phaseID,
|
||||
UpdateFrequency.PER_PHASE,
|
||||
);
|
||||
if (phaseSet) {
|
||||
info.setLayouts.push(phaseSet);
|
||||
}
|
||||
const batchSet = getProgramDescriptorSetLayout(
|
||||
device,
|
||||
lg,
|
||||
@@ -1293,6 +1284,15 @@ export class WebProgramLibrary implements ProgramLibrary {
|
||||
if (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);
|
||||
return programData.pipelineLayout;
|
||||
}
|
||||
|
||||
@@ -141,12 +141,27 @@ export class InstancedBuffer {
|
||||
|
||||
private _appendInstance (instance: IInstancedItem, data: Uint8Array, shader: Shader, descriptorSet: DescriptorSet): void {
|
||||
if (instance.count >= instance.capacity) { // resize buffers
|
||||
instance.capacity = Math.min(instance.capacity << 1, MAX_CAPACITY);
|
||||
const 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;
|
||||
const oldData = instance.data;
|
||||
instance.data = new Uint8Array(newSize);
|
||||
instance.data.set(oldData);
|
||||
instance.vb.resize(newSize);
|
||||
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;
|
||||
|
||||
@@ -1537,6 +1537,7 @@ export class Terrain extends Component {
|
||||
* @zh 获得地形信息
|
||||
*/
|
||||
@type(TerrainInfo)
|
||||
@visible(false)
|
||||
public get info (): TerrainInfo {
|
||||
const ti = new TerrainInfo();
|
||||
ti.tileSize = this.tileSize;
|
||||
|
||||
+54
-7
@@ -93,8 +93,8 @@ enum State {
|
||||
export enum ButtonEventType {
|
||||
/**
|
||||
* @event click
|
||||
* @param {Event.EventCustom} event
|
||||
* @param {Button} button - The Button component.
|
||||
* @param {EventTouch} event - The original touch event, undefined if the click is triggered by XR.
|
||||
*/
|
||||
CLICK = 'click',
|
||||
}
|
||||
@@ -156,16 +156,16 @@ export enum ButtonEventType {
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { log, Node } from 'cc';
|
||||
* import { log } from 'cc';
|
||||
* // Add an event to the button.
|
||||
* button.node.on(Node.EventType.TOUCH_START, (event) => {
|
||||
* log("This is a callback after the trigger event");
|
||||
* });
|
||||
* // You could also add a click event
|
||||
* // Note: In this way, you can't get the touch event info, so use it wisely.
|
||||
* button.node.on(Node.EventType.CLICK, (button) => {
|
||||
* //The event is a custom event, you could get the Button component via first argument
|
||||
* })
|
||||
* // The callback receives the Button component and the original touch event (if available).
|
||||
* button.on(Button.EventType.CLICK, (button, event) => {
|
||||
* log('button clicked');
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
@ccclass('cc.Button')
|
||||
@@ -586,6 +586,53 @@ export class Button extends Component {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* Register a Button event listener on the component. Button events are dispatched by the owner
|
||||
* node, and this method is a shorthand which forwards the registration to the node, so
|
||||
* `button.on(...)` and `button.node.on(...)` share the same listener registry.
|
||||
* @zh
|
||||
* 在组件上注册 Button 事件监听。Button 的事件由所属节点派发,此方法是 `this.node.on(type, ...)`
|
||||
* 的便捷封装,`button.on(...)` 与 `button.node.on(...)` 共用同一份监听器。
|
||||
* @param type @en Event type, e.g. [[ButtonEventType.CLICK]]. @zh 事件类型,如 [[ButtonEventType.CLICK]]。
|
||||
* @param callback @en The callback, receives the Button component and the original event. @zh 回调函数,参数为 Button 组件与原始事件。
|
||||
* @param target @en The target to be bound with. @zh 绑定的目标对象。
|
||||
* @example
|
||||
* ```ts
|
||||
* button.on(Button.EventType.CLICK, (button, event) => {
|
||||
* // clicked
|
||||
* }, this);
|
||||
* ```
|
||||
*/
|
||||
public on (type: ButtonEventType, callback: (button: Button, event?: EventTouch) => void, target?: unknown): void {
|
||||
this.node.on(type, callback, target);
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* Remove a Button event listener registered via [[on]] or `button.node.on`. To remove a listener,
|
||||
* the `type`, `callback` and `target` must match the registration.
|
||||
* @zh
|
||||
* 移除通过 [[on]] 或 `button.node.on` 注册的 Button 事件监听。`type`、`callback`、`target`
|
||||
* 需与注册时一致才能正确移除。
|
||||
*/
|
||||
public off (type: ButtonEventType, callback?: (button: Button, event?: EventTouch) => void, target?: unknown): void {
|
||||
this.node.off(type, callback, target);
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* Remove all Button event listeners registered with the given target.
|
||||
* Note: this forwards to `node.targetOff`, so listeners registered by other components
|
||||
* or by the engine internals on the same node with the same target are removed as well.
|
||||
* @zh
|
||||
* 移除指定 target 上注册的所有 Button 事件监听。注意:此方法会转发到 `node.targetOff`,
|
||||
* 同一节点上其他组件或引擎内部以相同 target 注册的监听也会被一并移除。
|
||||
*/
|
||||
public targetOff (target: unknown): void {
|
||||
this.node.targetOff(target);
|
||||
}
|
||||
|
||||
public __preload (): void {
|
||||
if (!this.target) {
|
||||
this.target = this.node;
|
||||
@@ -892,7 +939,7 @@ export class Button extends Component {
|
||||
|
||||
if (this._pressed) {
|
||||
ComponentEventHandler.emitEvents(this.clickEvents, event);
|
||||
this.node.emit(ButtonEventType.CLICK, this);
|
||||
this.node.emit(ButtonEventType.CLICK, this, event);
|
||||
}
|
||||
this._pressed = false;
|
||||
this._updateState();
|
||||
|
||||
@@ -41,6 +41,7 @@ import { InputFlag, InputMode, KeyboardReturnType } from './types';
|
||||
import { EditBoxImplBase } from './edit-box-impl-base';
|
||||
import { BrowserType, OS } from '../../../pal/system-info/enum-type';
|
||||
import { ccwindow } from '../../core/global-exports';
|
||||
import { getCanvasFontFamily } from '../../2d/utils/font-family';
|
||||
|
||||
const ccdocument = ccwindow.document;
|
||||
|
||||
@@ -519,7 +520,7 @@ export class EditBoxImpl extends EditBoxImplBase {
|
||||
|
||||
let font = textLabel.font;
|
||||
if (font && !(font instanceof BitmapFont)) {
|
||||
font = font._fontFamily;
|
||||
font = getCanvasFontFamily(textLabel as Label);
|
||||
} else {
|
||||
font = textLabel.fontFamily;
|
||||
}
|
||||
@@ -570,7 +571,7 @@ export class EditBoxImpl extends EditBoxImplBase {
|
||||
|
||||
let font = placeholderLabel.font;
|
||||
if (font && !(font instanceof BitmapFont)) {
|
||||
font = placeholderLabel.font._fontFamily;
|
||||
font = getCanvasFontFamily(placeholderLabel as Label);
|
||||
} else {
|
||||
font = placeholderLabel.fontFamily;
|
||||
}
|
||||
@@ -610,9 +611,12 @@ export class EditBoxImpl extends EditBoxImplBase {
|
||||
break;
|
||||
}
|
||||
|
||||
styleEl!.innerHTML = `#${this._domId}::-webkit-input-placeholder{text-transform: initial;-family: ${font};font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`
|
||||
+ `#${this._domId}::-moz-placeholder{text-transform: initial;-family: ${font};font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`
|
||||
+ `#${this._domId}::-ms-input-placeholder{text-transform: initial;-family: ${font};font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`;
|
||||
styleEl!.innerHTML = `#${this._domId}::-webkit-input-placeholder{text-transform: initial;-family: ${font};`
|
||||
+ `font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`
|
||||
+ `#${this._domId}::-moz-placeholder{text-transform: initial;-family: ${font};`
|
||||
+ `font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`
|
||||
+ `#${this._domId}::-ms-input-placeholder{text-transform: initial;-family: ${font};`
|
||||
+ `font-size: ${fontSize}px;color: ${fontColor};line-height: ${lineHeight}px;text-align: ${horizontalAlign};}`;
|
||||
// EDGE_BUG_FIX: hide clear button, because clearing input box in Edge does not emit input event
|
||||
// issue refference: https://github.com/angular/angular/issues/26307
|
||||
if (sys.browserType === BrowserType.EDGE) {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
# Worker 使用与维护
|
||||
|
||||
Worker 分为两个可选引擎功能:`worker` 提供 `createWorker`、`getWorkerCapabilities`、
|
||||
`checkWorkerScript` 等基础 API;额外启用 `worker-pool` 才提供 `WorkerPool`。
|
||||
它们不会自动把渲染、物理、音频或业务逻辑移到其他线程。
|
||||
|
||||
## 安装与构建
|
||||
|
||||
正式依赖是 `@cocos/engine-pal`,当前锁文件解析为 `1.0.5`,包含 Worker 平台实现。在 cocos4 根目录执行:
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run build
|
||||
```
|
||||
|
||||
`npm run build` 先生成压缩 JS,再生成声明。日志中的 `Performance` 只统计模块分析和摇树,
|
||||
后续压缩、source map 与写文件仍可能耗时数分钟,不能据此判断构建完成。
|
||||
`build:min` 每 15 秒输出累计耗时,正常完成后输出完成提示,失败时退出码为 1。
|
||||
是否成功仍以整个命令正常退出为准;进度提示不代表完成百分比。
|
||||
|
||||
`npm ci` 的 `postinstall` 会运行 `scripts/spread-pal.cjs`,将安装包的 `dist/` 复制到引擎 `pal/`。
|
||||
`pal/.pal-source.json` 记录复制来源和版本。`pal/` 是生成目录,不提交,不直接修改。
|
||||
仅拉取引擎代码、没有更新依赖,不等于已经安装新版 PAL。可检查:
|
||||
|
||||
```sh
|
||||
node -p "require('./node_modules/@cocos/engine-pal/package.json').version"
|
||||
```
|
||||
|
||||
本地修改 PAL 源码时,在 `cocos-pal` 构建后,从 cocos4 根目录同步:
|
||||
|
||||
```sh
|
||||
node scripts/spread-pal.cjs --source ../cocos-pal/dist
|
||||
npm run build
|
||||
```
|
||||
|
||||
显式本地来源不会被构建检查自动换成 npm 包;恢复正式包时执行不带 `--source` 的
|
||||
`node scripts/spread-pal.cjs`。
|
||||
|
||||
## 启用功能与选择模式
|
||||
|
||||
在 Creator 的引擎功能裁剪配置中展开 **Worker** 分组,按需要勾选子项(两项默认均关闭):
|
||||
|
||||
| 功能 | ccbuild 的 features | 从 cc 可用的能力 |
|
||||
| --- | --- | --- |
|
||||
| 基础 Worker 功能 | `['worker']` | 创建 Worker、收发消息、查询能力,由开发者管理生命周期 |
|
||||
| Worker Pool | `['worker-pool']` | 基础 Worker API,以及任务池、队列、超时和安全同步降级 |
|
||||
|
||||
分组标题的勾选框是全选/清空:只选基础 Worker 时显示半选;全选会同时启用 Worker Pool。
|
||||
勾选 Worker Pool 会关联开启基础 Worker;取消基础 Worker 时也会取消 Worker Pool。
|
||||
功能 ID 与项目已有配置保持兼容,无需迁移 `cache` 或 `includeModules`。
|
||||
|
||||
`worker-pool` 依赖 `worker`,Creator 会关联该依赖;直接调用 ccbuild 时,选择 `worker-pool`
|
||||
也会包含两者的导出入口。`exports/worker.ts` 与 `exports/worker-pool.ts` 分别提供公开 API,
|
||||
`cocos/misc/index.ts` 不导出它们。只启用 `worker` 的构建不包含线程池调度器;两项均不启用时,
|
||||
也会裁掉基础 Worker API 及其 PAL Worker 依赖。完整引擎预构建仍会生成所有模块,项目构建时才按配置裁剪。
|
||||
|
||||
**迁移已有项目:** 之前只启用 `worker` 且使用了 `WorkerPool` 的项目,需要额外启用 `worker-pool`,
|
||||
并重新构建。仅手动管理 Worker 的项目保留 `worker` 即可。`cc` 导入名称及运行时协议不变。
|
||||
|
||||
- **脚本模式**:`new WorkerPool('workers/task.js', options)`,适用于 Web 和提供 Worker 的小游戏环境。
|
||||
- **函数模式**:`new WorkerPool(fn, options)`,Web 在具备 Worker、Blob、对象 URL 能力时创建真实 Worker;
|
||||
不支持时在主线程执行原函数。函数必须自包含,不能捕获外部变量。
|
||||
- **自定义消息服务**:`createWorker(path)` 返回 `postMessage/onMessage/onError/terminate` 接口。
|
||||
它不提供任务池协议或自动同步 fallback。长期音频、网络等消息服务应自行管理消息和生命周期。
|
||||
|
||||
仅启用 `worker` 时可以这样自行管理:
|
||||
|
||||
```ts
|
||||
import { createWorker, getWorkerCapabilities } from 'cc';
|
||||
|
||||
if (getWorkerCapabilities().available) {
|
||||
const worker = createWorker('workers/service.js');
|
||||
worker.onMessage(result => console.log(result));
|
||||
worker.onError(error => { console.error(error); worker.terminate(); });
|
||||
worker.postMessage({ command: 'compute', value: 21 });
|
||||
// 在服务结束或组件销毁时调用 worker.terminate()。
|
||||
} else {
|
||||
// 由业务自行处理无 Worker 的情况。
|
||||
}
|
||||
```
|
||||
|
||||
原生和 Node.js 的 PAL Worker 入口报告不支持 JS Worker,不因宿主偶然存在全局 `Worker` 而创建它。
|
||||
池可在主线程执行函数或显式 fallback;原生子系统自身的线程策略由原生实现决定。
|
||||
|
||||
## 脚本模式最小示例
|
||||
|
||||
复制 [`cc-worker-template.js`](./cc-worker-template.js) 到项目构建输出的 `workers/task.js`,
|
||||
在其 `runTask(args)` 中实现计算逻辑。模板兼容 Web `self` 和小游戏 `worker` 消息入口。
|
||||
|
||||
```ts
|
||||
import { WorkerPool } from 'cc';
|
||||
|
||||
const pool = new WorkerPool('workers/task.js', {
|
||||
maxWorkers: 4,
|
||||
timeout: 5000,
|
||||
fallback: (n: number) => n * 2, // 必须与脚本计算等价,并允许安全重试
|
||||
});
|
||||
try {
|
||||
const result = await pool.run<number>([21]);
|
||||
console.log(result, pool.backend, pool.concurrency);
|
||||
} finally {
|
||||
pool.terminate();
|
||||
}
|
||||
```
|
||||
|
||||
对应脚本中的任务函数为:
|
||||
|
||||
```js
|
||||
function runTask(args) {
|
||||
return args[0] * 2;
|
||||
}
|
||||
```
|
||||
|
||||
脚本接收 `{ id, args }`,回复 `{ id, ok: true, value }` 或 `{ id, ok: false, error }`。
|
||||
自定义脚本必须保留该协议。主线程场景对象、DOM、闭包变量无法直接在 Worker 内使用。
|
||||
|
||||
引擎不会自动复制项目 Worker 脚本或修改小游戏打包配置。必须保证:
|
||||
|
||||
1. Web 的脚本路径能在最终部署地址访问,且满足同源和安全策略要求。
|
||||
2. 小游戏脚本位于平台声明的 Worker 目录内。微信在构建产物 `game.json` 中配置
|
||||
`"workers": "workers"`;分包脚本需先下载分包。
|
||||
3. 微信 Worker 的 `require` 依赖也在 Worker 目录内;该目录只放 JS 文件。
|
||||
|
||||
完整示例见 [`examples/worker-demo.ts`](./examples/worker-demo.ts) 和
|
||||
[`examples/prime-worker.js`](./examples/prime-worker.js)。需启用 Worker Pool 功能并打包脚本。
|
||||
示例耗时包含启动、消息传递和计算成本,加速比不是通过标准。
|
||||
|
||||
## 能力检测与微信 V1/V2
|
||||
|
||||
```ts
|
||||
import { getWorkerCapabilities, checkWorkerScript } from 'cc';
|
||||
|
||||
console.log(getWorkerCapabilities());
|
||||
console.log(checkWorkerScript('workers/task.js'));
|
||||
```
|
||||
|
||||
`available` 表示平台报告存在 Worker 能力;`parallel` 表示并发上限大于 1。
|
||||
它们不保证特定脚本可以运行。实际池状态应看 `pool.backend`(`worker / sync / none`),
|
||||
实际池大小看 `pool.concurrency`。Web 的脚本加载和执行错误可能在创建后才异步报告。
|
||||
|
||||
PAL 1.0.5 对非标准小游戏 Worker 的并发上限保守设为 1,对标准 Worker 和 Web 不设固定平台上限;
|
||||
实际创建数量仍受 `maxWorkers`、设备与运行时限制,创建可能失败。
|
||||
|
||||
微信 V1/V2 都使用 `wx.createWorker(path)`。PAL 以
|
||||
`wx.env.isSupportStandardWorker === true` 判断标准 Worker 能力,未提供或为 false 时按单 Worker、
|
||||
无 transfer 处理,不根据系统类型或版本号强行开启。`useExperimentalWorker` 不是 V2 开关。
|
||||
基础库、客户端、灰度和开发者工具的当前支持范围,应查阅微信官方文档并在目标环境验证;
|
||||
版本达标也不能代替能力检测。
|
||||
|
||||
标准 Worker 支持的 OffscreenCanvas、音频和网络能力不等于引擎会自动使用它们。
|
||||
Canvas 需由主线程通过 `transferControlToOffscreen()` 转移;Worker 内平台 API 使用 `worker.xxx`。
|
||||
SharedArrayBuffer 在消息中共享,不放入 transfer 列表;跨 realm 检测可用
|
||||
`buffer?.constructor?.name === 'SharedArrayBuffer'`,避免依赖 `instanceof`。
|
||||
|
||||
## 失败恢复、transfer 与 recheck
|
||||
|
||||
脚本后端由 PAL 选择:优先平台 Worker;适用时再尝试全局 Web Worker;都不可用时使用显式
|
||||
`options.fallback`。没有 fallback 则任务拒绝。函数模式不支持 Worker 时直接执行原函数。
|
||||
|
||||
- `timeout` 默认 0,表示关闭。生产脚本建议按最坏任务耗时设置超时,以处理永不回复的 Worker。
|
||||
- 脚本创建失败、忙时错误、超时、畸形回复和发送异常属于基础设施失败。有 fallback 时,池降级为同步执行。
|
||||
- 未移交所有权的失败任务可用 fallback 重算;已经 transfer 的任务拒绝,后续任务使用同步 fallback。
|
||||
业务必须保证 fallback 可安全重试。
|
||||
- 同一次降级中,其他忙碌 Worker 完成后退役;它们随后失败时,未 transfer 的任务仍可恢复。
|
||||
`retired` 只表示不再复用,不能单独作为禁止 fallback 的依据。
|
||||
- `recheck()` 刷新能力并选择新后端,推进后端代次;检查前的旧 Worker 失败只拒绝其原任务,
|
||||
不会再次熔断新后端。排队任务交给新后端,或在无后端且无 fallback 时拒绝。
|
||||
- Worker 正常返回 `{ ok: false }` 属于任务计算错误,直接拒绝,不触发基础设施降级。
|
||||
- 函数模式的运行时故障不自动在主线程重放原函数,避免将可能死锁的函数移到主线程。
|
||||
|
||||
`run(args, transfer)` 可能移交缓冲区所有权。需要恢复数据时应保留副本或能够重新生成参数。
|
||||
脚本模板不自动 transfer 返回值;Web 函数模式 bootstrap 会递归收集可转移返回值,
|
||||
处理循环引用、深层对象、自有属性和去重,SharedArrayBuffer 不参与 transfer。
|
||||
|
||||
正式构建使用错误编号,完整说明保留在 `EngineErrorMap.md` 的 16500—16516 条目;
|
||||
调试构建保留详细消息。诊断参数、任务拒绝和降级行为在正式构建中仍然有效。
|
||||
|
||||
## 平台抽象与旧 PAL 兼容
|
||||
|
||||
`cocos/misc/worker-pool.ts` 只负责调度、队列、超时和恢复;`worker.ts` 管理能力快照及后端缓存。
|
||||
平台 API、脚本检查、消息适配和函数 bootstrap 位于 `cocos-pal/src/worker`。
|
||||
`cc.config.json` 将 `pal/worker` 映射到 web、minigame、native、nodejs 入口。
|
||||
|
||||
`@types/pal/worker.d.ts` 提供引擎侧独立类型契约,`tests/scripts/pal-worker-types.test.cjs`
|
||||
校验其与已安装 PAL 的声明一致。它不依赖生成的兼容声明文件。
|
||||
|
||||
安装与各仓库构建入口调用统一的 `scripts/ensure-pal.cjs`:
|
||||
|
||||
1. npm 来源的 `pal/` 与已安装包版本不同:重新复制整个 PAL。
|
||||
2. Worker 缺失或为引擎兼容实现,来源已有真实实现:恢复真实 Worker。
|
||||
3. 来源完全没有 Worker:生成 JS 单线程兼容实现,支持未更新依赖的旧环境构建。
|
||||
4. 已有真实 Worker 实现:不做局部覆盖;不完整的真实模块需要重新执行 spread 修复。
|
||||
|
||||
兼容实现共享文件为 `pal/worker/compat.js`,不生成根 `index.js`,避免绕过平台映射或留下解析缓存。
|
||||
来源为 `--source` 的目录只从该来源恢复;不会混入 npm 的 Worker。整个 `pal/` 缺失时仍需先安装依赖。
|
||||
这些检查不能代替安装新版本依赖;仅拉取引擎后继续使用旧 npm 包,仍可能使用同步兼容。
|
||||
编辑器绕过仓库构建脚本时,应先完成安装和 spread。
|
||||
|
||||
新增 PAL 检查可在 `scripts/ensure-pal.cjs` 增加独立函数并注册到 `checks`。
|
||||
检查必须幂等,修改返回 true,无需修改返回 false,无法继续构建时抛出错误。
|
||||
|
||||
## 测试与验收
|
||||
|
||||
在 cocos4 根目录执行:
|
||||
|
||||
```sh
|
||||
npm run test:pal
|
||||
npm test -- --runInBand
|
||||
node scripts/test-worker-release.cjs
|
||||
```
|
||||
|
||||
- `test:pal`:同步来源、旧 PAL 兼容、升级/降级、构建入口及类型契约。
|
||||
- `tests/misc/worker-*.test.ts`:实际 PAL 产物上的平台能力、Web/微信路径、队列、生命周期、超时、
|
||||
代次隔离、并发降级、transfer 和函数 bootstrap。平台 API 为可控替身;旧 PAL 专项使用兼容模块。
|
||||
- `test-worker-release.cjs`:实际编译仅 Worker、Worker Pool 及未启用两项功能的 HTML5 产物,
|
||||
检查导出、手动消息通信及 source map 模块清单,验证裁剪边界;同时保留正式错误编号、
|
||||
调度、消息协议、transfer 失败恢复及 recheck 检查。它要求安装带 Worker 的 PAL。
|
||||
|
||||
合入前还应在 cocos-test-projects 的 `assets/cases/scene/worker-test/worker.scene` 验收:
|
||||
|
||||
1. Web:对比主线程与 Worker 模式,确认结果一致、场景持续更新,池状态确为 `worker`;
|
||||
禁用 Worker API 后确认 fallback。反复切换模式和销毁场景,不应留下任务或线程。
|
||||
2. 微信:检查最终 `game.json` 和脚本文件,分别验证非标准单 Worker 环境和有标准能力标志的环境;
|
||||
验证脚本缺失、未下载分包、创建失败、超时与 transfer 后失败。
|
||||
3. 原生:确认不启动 JS Worker,函数或显式 fallback 在主线程运行。
|
||||
4. 裁剪:在相同构建参数下对比开启/关闭 Worker,分别记录原始和压缩包体;不能用旧包或不同配置比较。
|
||||
|
||||
自动测试和 ccbuild 成功不代表浏览器、开发者工具或真机已通过。验收记录应包含引擎提交、PAL 版本、
|
||||
平台/客户端环境、构建参数、池状态与结果;不得把 `sync` fallback 当成真实 Worker 成功。
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Cocos universal worker entry template (Web + WeChat mini-game).
|
||||
*
|
||||
* This is a READY-MADE worker file you copy into your own project. It implements the exact message
|
||||
* protocol expected by the engine's `cc.WorkerPool` (script mode) and `cc.createWorker(path)`, and it
|
||||
* runs on BOTH Web (`self.onmessage`) and WeChat (`worker.onMessage`) with no further changes.
|
||||
*
|
||||
* WHY A PHYSICAL FILE IS REQUIRED ON WECHAT
|
||||
* -----------------------------------------
|
||||
* WeChat mini-games have no global `Worker` constructor and FORBID dynamically executing JS code
|
||||
* (`eval` / `new Function` are banned). So the engine cannot ship a function's source string and
|
||||
* rebuild it inside a WeChat worker. The only way to get real parallelism on WeChat is to write the
|
||||
* task into a physical JS file like this one, package it, and declare it in `game.json`.
|
||||
*
|
||||
* HOW TO USE
|
||||
* ----------
|
||||
* Enable the `worker-pool` engine feature (which depends on `worker`) for the pool example below.
|
||||
* `createWorker(path)` alone only requires `worker`; the caller manages its message protocol.
|
||||
* 1. Copy this file into your project's worker directory, e.g. `workers/heavy-compute/index.js`.
|
||||
* 2. Implement your pure computation in `runTask(args)` below. It MUST be self-contained: it runs in
|
||||
* a separate thread and CANNOT access `cc`, the scene, the DOM, or any closure variable from the
|
||||
* main thread. Only `args` (structured-cloned) is available as input, and the return value must be
|
||||
* structured-cloneable (or a Transferable such as ArrayBuffer / TypedArray).
|
||||
* 3. Package & configure:
|
||||
* - WeChat: declare the worker root in the built `game.json` -> { "workers": "workers" }, and make
|
||||
* sure this file lives inside that directory. WeChat V1 allows only ONE worker at a time; V2
|
||||
* (standard worker, gray release / Android) allows multiple. The engine pool auto-caps to the
|
||||
* platform limit, so you do not need to branch on this yourself.
|
||||
* - Web: make sure this file is served at the same path you pass to the pool.
|
||||
* 4. Drive it from the main thread:
|
||||
* // Pool size defaults to a CPU-based count and is auto-capped per platform (WeChat V1 => 1).
|
||||
* // On WeChat V2 pass an explicit maxWorkers to scale beyond 1 (core count is not detectable there).
|
||||
* const pool = new cc.WorkerPool('workers/heavy-compute/index.js', { maxWorkers: 4 });
|
||||
* const result = await pool.run([1000000]); // args array -> runTask(args)
|
||||
* pool.terminate();
|
||||
*
|
||||
* MESSAGE PROTOCOL (must match the engine; do not change the plumbing below)
|
||||
* --------------------------------------------------------------------------
|
||||
* main -> worker : { id: number, args: any[] }
|
||||
* worker -> main : { id: number, ok: true, value: any }
|
||||
* | { id: number, ok: false, error: string }
|
||||
*/
|
||||
|
||||
// ==== YOUR TASK: put your pure, self-contained computation here ==================
|
||||
function runTask (args) {
|
||||
// `args` is exactly the array you passed to `pool.run([...])`.
|
||||
// Example below: a heavy numeric loop. Replace it with your own logic.
|
||||
var n = (args && args[0]) || 0;
|
||||
var acc = 0;
|
||||
for (var i = 0; i < n; i++) {
|
||||
acc += Math.sqrt(i);
|
||||
}
|
||||
return acc;
|
||||
|
||||
// ---- Multi-task variant (optional) -------------------------------------------
|
||||
// If one worker file should handle several kinds of work, dispatch on an argument:
|
||||
// switch (args && args[0]) {
|
||||
// case 'normals': return computeNormals(args[1]);
|
||||
// case 'lod': return computeLod(args[1]);
|
||||
// default: throw new Error('unknown task: ' + (args && args[0]));
|
||||
// }
|
||||
// Remember: every helper you call (computeNormals, ...) must also be defined in THIS file
|
||||
// (or required from another file inside the same worker directory).
|
||||
}
|
||||
// =================================================================================
|
||||
|
||||
// ---- Message plumbing (works on Web and WeChat; normally no need to edit) --------
|
||||
|
||||
function handleMessage (msg) {
|
||||
var id = msg && msg.id;
|
||||
try {
|
||||
var value = runTask(msg && msg.args);
|
||||
reply({ id: id, ok: true, value: value });
|
||||
} catch (e) {
|
||||
reply({ id: id, ok: false, error: String((e && e.message) || e) });
|
||||
}
|
||||
}
|
||||
|
||||
function reply (msg) {
|
||||
// WeChat mini-game: the global `worker` object.
|
||||
if (typeof worker !== 'undefined' && worker && typeof worker.postMessage === 'function') {
|
||||
worker.postMessage(msg);
|
||||
return;
|
||||
}
|
||||
// Web Worker: the global `self`.
|
||||
if (typeof self !== 'undefined' && typeof self.postMessage === 'function') {
|
||||
self.postMessage(msg);
|
||||
}
|
||||
}
|
||||
|
||||
// Register the message handler for the current platform (mutually exclusive).
|
||||
if (typeof worker !== 'undefined' && worker && typeof worker.onMessage === 'function') {
|
||||
// WeChat mini-game worker.
|
||||
worker.onMessage(handleMessage);
|
||||
} else if (typeof self !== 'undefined') {
|
||||
// Web Worker.
|
||||
self.onmessage = function (e) {
|
||||
handleMessage(e && e.data);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* WorkerPool 脚本模式示例:同时提交 4 个计算任务,并与主线程结果比较。
|
||||
*
|
||||
* 1. 在引擎功能配置中启用 worker-pool(会依赖 worker)。
|
||||
* 2. 将 prime-worker.js 打包为 workers/prime-worker.js;微信还需配置 game.json 的 workers 目录。
|
||||
* 3. 将此组件挂到场景节点,检查结果一致性、实际 pool.backend 和 pool.concurrency。
|
||||
*
|
||||
* Web 和标准小游戏 Worker 可按能力并发,其他小游戏 Worker 可能只有一个槽位。
|
||||
* 没有可用 Worker 或发生安全可恢复的故障时,显式 fallback 在主线程执行。
|
||||
* 计时包含 Worker 启动、消息传递和计算,设备、任务大小和预热都会影响结果;
|
||||
* 不能用单次加速比判断平台支持性,也不能把 sync fallback 当成 Worker 成功。
|
||||
*/
|
||||
import {
|
||||
_decorator, Component, WorkerPool, checkWorkerScript, getWorkerCapabilities,
|
||||
} from 'cc';
|
||||
|
||||
const { ccclass } = _decorator;
|
||||
|
||||
const WORKER_PATH = 'workers/prime-worker.js';
|
||||
const LIMIT = 200_000; // 计算小于该值的素数个数;单任务约 100~300ms,可按机器性能调整
|
||||
const TASKS = 4;
|
||||
// worker 收下消息却永不回复时的兜底(死锁 / 无限循环 / 平台静默丢消息)。
|
||||
// 触发后 Worker 被驱逐,本示例通过 fallback 重算并降级。0 = 关闭。
|
||||
const TIMEOUT = 10_000;
|
||||
|
||||
// 与 prime-worker.js 中 runTask(args) 完全一致的算法:
|
||||
// 1) 作为串行基线计时;2) 作为无 worker 后端时的单线程降级(options.fallback)。
|
||||
// 两处必须保持同步——demo 会对比二者结果来证明 worker 链路计算正确。
|
||||
function countPrimes (limit: number): number {
|
||||
let count = 0;
|
||||
for (let n = 2; n < limit; n++) {
|
||||
let isPrime = true;
|
||||
for (let d = 2; d * d <= n; d++) {
|
||||
if (n % d === 0) { isPrime = false; break; }
|
||||
}
|
||||
if (isPrime) { count++; }
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
@ccclass('WorkerDemo')
|
||||
export class WorkerDemo extends Component {
|
||||
public start (): void {
|
||||
this.benchmark().catch((e) => {
|
||||
console.error('[WorkerDemo] benchmark failed:', e);
|
||||
});
|
||||
}
|
||||
|
||||
private async benchmark (): Promise<void> {
|
||||
// 0a) 平台能力快照——业务决定"要不要开这个特性"的正确依据。
|
||||
// 注意 parallel 与 available 的区别:7 个小游戏平台 available 为真但 parallel 为假。
|
||||
const caps = getWorkerCapabilities();
|
||||
console.log(`[WorkerDemo] capabilities: available=${caps.available} `
|
||||
+ `parallel=${caps.parallel} concurrencyLimit=${caps.concurrencyLimit} `
|
||||
+ `transfer=${caps.supportsTransfer} sab=${caps.supportsSharedArrayBuffer}`);
|
||||
console.log(`[WorkerDemo] capability reason: ${caps.reason}`);
|
||||
|
||||
// 0b) 脚本路径预检:文件是否真的在代码包里、路径是否合法。
|
||||
// 引擎内部也做同样的检查来决定后端:平台 worker → Web Worker → fallback 单线程 → 报错。
|
||||
const status = checkWorkerScript(WORKER_PATH);
|
||||
console.log(`[WorkerDemo] checkWorkerScript: ready=${status.ready} `
|
||||
+ `version=${status.version} reason="${status.reason}"`);
|
||||
|
||||
// 1) 串行基线:主线程连续算 TASKS 次。
|
||||
const t0 = Date.now();
|
||||
let expected = 0;
|
||||
for (let i = 0; i < TASKS; i++) {
|
||||
expected = countPrimes(LIMIT);
|
||||
}
|
||||
const serialMs = Date.now() - t0;
|
||||
|
||||
// 2) WorkerPool 并行:后端由引擎自动解析,池大小自动按平台 concurrencyLimit 封顶
|
||||
// (7 个单 worker 平台 + 微信 V1 → 1;微信 V2 / Web → maxWorkers)。
|
||||
const pool = new WorkerPool(WORKER_PATH, {
|
||||
maxWorkers: TASKS,
|
||||
timeout: TIMEOUT,
|
||||
fallback: countPrimes, // 无任何 worker 后端时单线程兜底,保证 demo 总能跑通
|
||||
});
|
||||
console.log(`[WorkerDemo] resolved backend: ${pool.backend}`);
|
||||
|
||||
const t1 = Date.now();
|
||||
let results: number[];
|
||||
try {
|
||||
results = await Promise.all(
|
||||
Array.from({ length: TASKS }, () => pool.run<number>([LIMIT])),
|
||||
);
|
||||
} finally {
|
||||
pool.terminate();
|
||||
}
|
||||
const poolMs = Date.now() - t1;
|
||||
|
||||
// 3) 验证:所有任务结果必须与串行基线一致。
|
||||
const allMatch = results.every((r) => r === expected);
|
||||
console.log(`[WorkerDemo] primes below ${LIMIT} = ${expected}, results match: ${allMatch}`);
|
||||
|
||||
const speedup = serialMs / Math.max(1, poolMs);
|
||||
console.log(`[WorkerDemo] serial: ${serialMs}ms | pool(${TASKS} tasks): ${poolMs}ms `
|
||||
+ `| speedup: ${speedup.toFixed(2)}x`);
|
||||
|
||||
// 启动和通信成本也在计时内。以结果和实际后端验收,不用加速比推断是否正确。
|
||||
if (pool.backend === 'sync') {
|
||||
console.warn('[WorkerDemo] 池已走 fallback 单线程执行,请检查平台能力、脚本打包和运行时降级日志。');
|
||||
} else if (pool.concurrency <= 1) {
|
||||
console.log('[WorkerDemo] 当前池只使用 1 个 Worker,任务可异步卸载,但不会并行执行。');
|
||||
} else {
|
||||
console.log('[WorkerDemo] 当前池支持多个 Worker;实际收益需在目标设备上重复测量。');
|
||||
}
|
||||
|
||||
if (!allMatch) {
|
||||
throw new Error('[WorkerDemo] worker 脚本与 fallback 结果不一致,'
|
||||
+ '请检查 prime-worker.js 与 countPrimes 算法是否同步!');
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -145,7 +145,7 @@ void main() {
|
||||
color = packRGBE(color.rgb); // for reflection-map
|
||||
#else
|
||||
color = CCSurfacesDebugDisplayInvalidNumber(color);
|
||||
#if !CC_USE_FLOAT_OUTPUT || CC_IS_TRANSPARENCY_PASS
|
||||
#if !CC_USE_FLOAT_OUTPUT
|
||||
color.rgb = HDRToLDR(color.rgb);
|
||||
color.rgb = LinearToSRGB(color.rgb);
|
||||
#endif
|
||||
|
||||
@@ -346,6 +346,21 @@
|
||||
"enginePlugin": false,
|
||||
"category": "network"
|
||||
},
|
||||
"worker": {
|
||||
"default": false,
|
||||
"label": "i18n:ENGINE.features.worker.label",
|
||||
"description": "i18n:ENGINE.features.worker.description",
|
||||
"enginePlugin": true,
|
||||
"category": "worker"
|
||||
},
|
||||
"worker-pool": {
|
||||
"default": false,
|
||||
"label": "i18n:ENGINE.features.worker_pool.label",
|
||||
"description": "i18n:ENGINE.features.worker_pool.description",
|
||||
"enginePlugin": true,
|
||||
"category": "worker",
|
||||
"dependencies": ["worker"]
|
||||
},
|
||||
"terrain": {
|
||||
"default": true,
|
||||
"label": "i18n:ENGINE.features.terrain.label",
|
||||
@@ -498,6 +513,11 @@
|
||||
"checkable": true,
|
||||
"required": true
|
||||
},
|
||||
"worker": {
|
||||
"label": "i18n:ENGINE.features.categories.worker.label",
|
||||
"description": "i18n:ENGINE.features.categories.worker.description",
|
||||
"checkable": true
|
||||
},
|
||||
"2d": {
|
||||
"label": "i18n:ENGINE.features.categories.2d.label",
|
||||
"description": "i18n:ENGINE.features.categories.2d.description",
|
||||
|
||||
@@ -896,6 +896,10 @@ module.exports = link(mixin({
|
||||
},
|
||||
features: {
|
||||
categories: {
|
||||
worker: {
|
||||
label: 'Worker',
|
||||
description: 'Worker features. The group checkbox selects or clears all items; Worker Pool depends on Basic Worker.',
|
||||
},
|
||||
'2d': {
|
||||
label: '2D',
|
||||
description: '2D',
|
||||
@@ -1133,6 +1137,14 @@ module.exports = link(mixin({
|
||||
label: "WebSocket Server",
|
||||
description: "Enable WebSocket Server for native. Note: WebSocket must also be enabled.",
|
||||
},
|
||||
worker: {
|
||||
label: "Basic Worker",
|
||||
description: "Enable cross-platform Worker creation, messaging and capability queries. Manage workers yourself; enable Worker Pool separately for task scheduling and synchronous fallback.",
|
||||
},
|
||||
worker_pool: {
|
||||
label: "Worker Pool",
|
||||
description: "Enable WorkerPool task scheduling, queuing, timeouts and safe synchronous fallback. Depends on Worker.",
|
||||
},
|
||||
flags: {
|
||||
spine: {
|
||||
loadManual: {
|
||||
|
||||
@@ -874,6 +874,10 @@ module.exports = link(mixin({
|
||||
},
|
||||
features: {
|
||||
categories: {
|
||||
worker: {
|
||||
label: 'Worker',
|
||||
description: 'Worker 功能分组。分组勾选框用于全选或清空;Worker Pool 依赖基础 Worker 功能。',
|
||||
},
|
||||
'2d': {
|
||||
label: '2D',
|
||||
description: '2D',
|
||||
@@ -1111,6 +1115,14 @@ module.exports = link(mixin({
|
||||
label: "WebSocket Server",
|
||||
description: "对原生启用 WebSocket Server。注意: 必须同时启用 WebSocket。",
|
||||
},
|
||||
worker: {
|
||||
label: "基础 Worker 功能",
|
||||
description: "启用跨平台 Worker 创建、消息通信和能力查询,由开发者自行管理 Worker。需要任务调度与同步降级时,额外启用 Worker Pool。",
|
||||
},
|
||||
worker_pool: {
|
||||
label: "Worker Pool",
|
||||
description: "启用 WorkerPool 任务调度、队列、超时和安全同步降级。依赖 Worker 功能。",
|
||||
},
|
||||
flags: {
|
||||
spine: {
|
||||
loadManual: {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
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 engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/** Entry of the optional `worker-pool` feature, which depends on `worker`. */
|
||||
export { WorkerPool } from '../cocos/misc/worker-pool';
|
||||
export type { WorkerPoolOptions, WorkerExecutionMode } from '../cocos/misc/worker-pool';
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
Copyright (c) 2020 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 engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Entry of the optional `worker` feature.
|
||||
*
|
||||
* The worker API lives in `cocos/misc/worker.ts` but is intentionally NOT re-exported from
|
||||
* `cocos/misc/index.ts`: that file belongs to the always-on `base` feature, so anything exported
|
||||
* there ships in every build's main bundle. Routing the subsystem through this dedicated entry lets
|
||||
* builds omit the Worker API and its PAL dependencies when the feature is disabled.
|
||||
* Pool scheduling is separately enabled by the `worker-pool` feature.
|
||||
*
|
||||
* Only the public surface is re-exported here. Platform implementations live in `pal/worker`.
|
||||
* Internal backend selection and cache management stay off the `cc` namespace.
|
||||
*/
|
||||
|
||||
export {
|
||||
createWorker,
|
||||
isWorkerSupported,
|
||||
isSupportStandardWorker,
|
||||
checkWorkerScript,
|
||||
getWorkerConcurrencyLimit,
|
||||
getOptimalWorkerCount,
|
||||
getWorkerCapabilities,
|
||||
} from '../cocos/misc/worker';
|
||||
export type { WorkerTask, IWorkerScriptStatus } from '../cocos/misc/worker';
|
||||
|
||||
export type {
|
||||
IWorker,
|
||||
IWorkerBackend,
|
||||
IWorkerDiagnosis,
|
||||
IWorkerCapabilities,
|
||||
} from 'pal/worker';
|
||||
@@ -12,6 +12,7 @@ module.exports = {
|
||||
moduleNameMapper: {
|
||||
...pathsToModuleNameMapper(compilerOptions.paths, { prefix: `${__dirname}/` }),
|
||||
'external:(.*)': '<rootDir>/native/external/$1',
|
||||
'^pal/worker$': '<rootDir>/tests/mocks/pal-worker.js',
|
||||
},
|
||||
transformIgnorePatterns: [
|
||||
// ignore everything in the node_modules EXCEPT for:
|
||||
|
||||
@@ -660,6 +660,8 @@ elseif(OPENHARMONY)
|
||||
endif()
|
||||
|
||||
cocos_source_files(
|
||||
cocos/platform/interfaces/modules/canvas/CanvasFont.cpp
|
||||
cocos/platform/interfaces/modules/canvas/CanvasFont.h
|
||||
cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.cpp
|
||||
cocos/platform/interfaces/modules/canvas/CanvasRenderingContext2D.h
|
||||
cocos/platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h
|
||||
|
||||
@@ -27,6 +27,25 @@
|
||||
#include "core/assets/RenderingSubMesh.h"
|
||||
|
||||
namespace cc {
|
||||
|
||||
namespace {
|
||||
|
||||
// GPU buffers are allocated on demand, in vertex/index counts, keep in sync with
|
||||
// cocos/2d/assembler/graphics/constants.ts. Grow only: doResize re-creates the GPU buffer.
|
||||
constexpr uint32_t MAX_VERTEX_COUNT = 65536;
|
||||
constexpr uint32_t INDICES_PER_VERTEX = 3;
|
||||
constexpr uint32_t MAX_INDEX_COUNT = MAX_VERTEX_COUNT * INDICES_PER_VERTEX;
|
||||
|
||||
inline uint32_t growCapacity(uint32_t needed, uint32_t current, uint32_t maxCap) {
|
||||
uint32_t cap = current > 1U ? current : 1U;
|
||||
while (cap < needed) {
|
||||
cap *= 2;
|
||||
}
|
||||
return cap < maxCap ? cap : maxCap;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
UIModelProxy::UIModelProxy() {
|
||||
_device = Root::getInstance()->getDevice();
|
||||
}
|
||||
@@ -55,16 +74,20 @@ void UIModelProxy::activeSubModels() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Allocate exactly for the data of this chunk, rounded up to a power of two.
|
||||
const uint32_t vertexCapacity = growCapacity(drawInfo->getVertexOffset(), 0, MAX_VERTEX_COUNT);
|
||||
const uint32_t indexCapacity = growCapacity(drawInfo->getIndexOffset(), 0, MAX_INDEX_COUNT);
|
||||
|
||||
auto* vertexBuffer = _device->createBuffer({
|
||||
gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST,
|
||||
gfx::MemoryUsageBit::DEVICE,
|
||||
65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
vertexCapacity * _stride,
|
||||
_stride,
|
||||
});
|
||||
auto* indexBuffer = _device->createBuffer({
|
||||
gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST,
|
||||
gfx::MemoryUsageBit::DEVICE,
|
||||
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
static_cast<uint32_t>(indexCapacity * sizeof(uint16_t)),
|
||||
sizeof(uint16_t),
|
||||
});
|
||||
gfx::BufferList vbReference;
|
||||
@@ -87,24 +110,32 @@ void UIModelProxy::uploadData() {
|
||||
for (size_t i = 0; i < drawInfos.size(); i++) {
|
||||
auto* drawInfo = drawInfos[i];
|
||||
auto* ia = subModelList.at(i)->getInputAssembler();
|
||||
if (drawInfo->getVertexOffset() <= 0 || drawInfo->getIndexOffset() <= 0) continue;
|
||||
const uint32_t vertexCount = drawInfo->getVertexOffset();
|
||||
const uint32_t indexCount = drawInfo->getIndexOffset();
|
||||
if (vertexCount == 0 || indexCount == 0) continue;
|
||||
|
||||
gfx::BufferList vBuffers = ia->getVertexBuffers();
|
||||
if (!vBuffers.empty()) {
|
||||
auto size = drawInfo->getVertexOffset() * _stride;
|
||||
// if (size > vBuffers[0]->getSize()) {
|
||||
vBuffers[0]->resize(size);
|
||||
// }
|
||||
vBuffers[0]->update(drawInfo->getVDataBuffer()); // vdata
|
||||
gfx::Buffer* vBuffer = vBuffers[0];
|
||||
const uint32_t neededVBytes = vertexCount * _stride;
|
||||
if (neededVBytes > vBuffer->getSize()) {
|
||||
const uint32_t capacity = growCapacity(vertexCount, vBuffer->getSize() / _stride, MAX_VERTEX_COUNT);
|
||||
vBuffer->resize(capacity * _stride);
|
||||
}
|
||||
// pass the valid size explicitly, update(ptr) uploads the whole capacity
|
||||
vBuffer->update(drawInfo->getVDataBuffer(), neededVBytes); // vdata
|
||||
}
|
||||
ia->setVertexCount(drawInfo->getVertexOffset()); // count
|
||||
ia->setVertexCount(vertexCount); // count
|
||||
|
||||
gfx::Buffer* iBuffer = ia->getIndexBuffer();
|
||||
auto size = drawInfo->getIndexOffset() * 2;
|
||||
// if (size > iBuffer->getSize()) {
|
||||
iBuffer->resize(size);
|
||||
// }
|
||||
iBuffer->update(drawInfo->getIDataBuffer()); // idata
|
||||
ia->setIndexCount(drawInfo->getIndexOffset()); // indexCount
|
||||
const auto neededIBytes = static_cast<uint32_t>(indexCount * sizeof(uint16_t));
|
||||
if (neededIBytes > iBuffer->getSize()) {
|
||||
const uint32_t capacity = growCapacity(indexCount, static_cast<uint32_t>(iBuffer->getSize() / sizeof(uint16_t)),
|
||||
MAX_INDEX_COUNT);
|
||||
iBuffer->resize(static_cast<uint32_t>(capacity * sizeof(uint16_t)));
|
||||
}
|
||||
iBuffer->update(drawInfo->getIDataBuffer(), neededIBytes); // idata
|
||||
ia->setIndexCount(indexCount); // indexCount
|
||||
// drawInfo->setModel(_model); // hack, render by model
|
||||
}
|
||||
|
||||
|
||||
@@ -222,13 +222,22 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ccs
|
||||
// Fill index buffer.
|
||||
ArrayBuffer::Ptr indexBuffer;
|
||||
uint32_t idxCount = 0;
|
||||
const uint32_t idxStride = 2;
|
||||
uint32_t idxStride = 2;
|
||||
gfx::Format indexFormat = gfx::Format::R16UI;
|
||||
if (geometry.indices.has_value()) {
|
||||
const ccstd::vector<uint32_t> &indices = geometry.indices.value();
|
||||
uint32_t maxIndex = 0;
|
||||
for (uint32_t idx : indices) {
|
||||
maxIndex = std::max(maxIndex, idx);
|
||||
}
|
||||
if (maxIndex > std::numeric_limits<uint16_t>::max()) {
|
||||
idxStride = 4;
|
||||
indexFormat = gfx::Format::R32UI;
|
||||
}
|
||||
idxCount = static_cast<uint32_t>(indices.size());
|
||||
indexBuffer = ccnew ArrayBuffer(idxStride * idxCount);
|
||||
DataView indexBufferView(indexBuffer);
|
||||
writeBuffer(indexBufferView, indices, gfx::Format::R16UI);
|
||||
writeBuffer(indexBufferView, indices, indexFormat);
|
||||
}
|
||||
|
||||
// Create primitive.
|
||||
|
||||
@@ -86,6 +86,12 @@ void BakedSkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Me
|
||||
pipeline::UBOSkinning::size,
|
||||
});
|
||||
}
|
||||
|
||||
// JSB synchronizes the new root's animation buffer before calling bindSkeleton.
|
||||
for (index_t i = 0; i < _subModels.size(); ++i) {
|
||||
updateLocalDescriptors(i, _subModels[i]->getDescriptorSet());
|
||||
}
|
||||
updateInstancedJointTextureInfo();
|
||||
}
|
||||
|
||||
void BakedSkinningModel::updateTransform(uint32_t stamp) {
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
****************************************************************************/
|
||||
#include "3d/models/SkinningModel.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "3d/assets/Mesh.h"
|
||||
@@ -80,6 +82,7 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
|
||||
_joints.clear();
|
||||
|
||||
if (!skeleton || !skinningRoot || !mesh) return;
|
||||
const bool prevRealTimeTextureMode = _realTimeTextureMode;
|
||||
auto jointCount = static_cast<uint32_t>(skeleton->getJoints().size());
|
||||
_realTimeTextureMode = pipeline::SkinningJointCapacity::jointUniformCapacity < jointCount;
|
||||
setTransform(skinningRoot);
|
||||
@@ -113,6 +116,15 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
|
||||
jointInfo.indices = std::move(indices);
|
||||
_joints.emplace_back(std::move(jointInfo));
|
||||
}
|
||||
|
||||
// Rebind recreated resources without resetting custom instanced attributes.
|
||||
const auto subModelCount = std::min(_subModels.size(), _bufferIndices.size());
|
||||
if (subModelCount && prevRealTimeTextureMode != _realTimeTextureMode) {
|
||||
onMacroPatchesStateChanged();
|
||||
}
|
||||
for (index_t i = 0; i < subModelCount; ++i) {
|
||||
updateLocalDescriptors(i, _subModels[i]->getDescriptorSet());
|
||||
}
|
||||
}
|
||||
|
||||
void SkinningModel::updateTransform(uint32_t stamp) {
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
#include <sys/types.h>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
#include "application/ApplicationManager.h"
|
||||
#include "audio/include/AudioEngine.h"
|
||||
@@ -265,10 +266,11 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
|
||||
|
||||
auto iter = _callbackMap.find(id);
|
||||
if (iter != _callbackMap.end()) {
|
||||
if (state == IAudioPlayer::State::OVER) {
|
||||
iter->second(id, filePath);
|
||||
}
|
||||
auto callback = std::move(iter->second);
|
||||
_callbackMap.erase(iter);
|
||||
if (state == IAudioPlayer::State::OVER) {
|
||||
callback(id, filePath);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
|
||||
#import <OpenAL/al.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include "base/std/container/string.h"
|
||||
|
||||
@@ -40,6 +42,7 @@
|
||||
namespace cc {
|
||||
class AudioEngineImpl;
|
||||
class AudioPlayer;
|
||||
class Scheduler;
|
||||
|
||||
class AudioCache {
|
||||
public:
|
||||
@@ -96,13 +99,15 @@ protected:
|
||||
|
||||
std::mutex _readDataTaskMutex;
|
||||
|
||||
State _state{State::INITIAL};
|
||||
std::atomic<State> _state{State::INITIAL};
|
||||
|
||||
std::shared_ptr<bool> _isDestroyed;
|
||||
// Assigned before the read task is submitted; workers must not look up the current application.
|
||||
std::weak_ptr<Scheduler> _scheduler;
|
||||
std::shared_ptr<std::atomic_bool> _isDestroyed;
|
||||
ccstd::string _fileFullPath;
|
||||
unsigned int _id;
|
||||
bool _isLoadingFinished{false};
|
||||
bool _isSkipReadDataTask{false};
|
||||
std::atomic_bool _isLoadingFinished{false};
|
||||
std::atomic_bool _isSkipReadDataTask{false};
|
||||
|
||||
friend class AudioEngineImpl;
|
||||
friend class AudioPlayer;
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <OpenAL/alc.h>
|
||||
#include <thread>
|
||||
#include "application/ApplicationManager.h"
|
||||
#include "base/Scheduler.h"
|
||||
#include "base/memory/Memory.h"
|
||||
|
||||
@@ -85,7 +84,7 @@ unsigned int __idIndex = 0;
|
||||
using namespace cc;
|
||||
|
||||
AudioCache::AudioCache()
|
||||
: _isDestroyed(std::make_shared<bool>(false)), _id(++__idIndex){
|
||||
: _isDestroyed(std::make_shared<std::atomic_bool>(false)), _id(++__idIndex){
|
||||
ALOGVV("AudioCache() %p, id=%u", this, _id);
|
||||
for (int i = 0; i < QUEUEBUFFER_NUM; ++i) {
|
||||
_queBuffers[i] = nullptr;
|
||||
@@ -114,7 +113,7 @@ AudioCache::~AudioCache() {
|
||||
_alBufferId = INVALID_AL_BUFFER_ID;
|
||||
}
|
||||
} else {
|
||||
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state);
|
||||
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, static_cast<int>(_state.load()));
|
||||
}
|
||||
|
||||
if (_queBufferFrames > 0) {
|
||||
@@ -267,7 +266,6 @@ void AudioCache::readDataTask(unsigned int selfId) {
|
||||
invokingPlayCallbacks();
|
||||
invokingLoadCallbacks();
|
||||
|
||||
_isLoadingFinished = true;
|
||||
if (_state != State::READY) {
|
||||
_state = State::FAILED;
|
||||
if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId)) {
|
||||
@@ -277,12 +275,13 @@ void AudioCache::readDataTask(unsigned int selfId) {
|
||||
}
|
||||
}
|
||||
|
||||
_isLoadingFinished = true;
|
||||
_readDataTaskMutex.unlock();
|
||||
}
|
||||
|
||||
void AudioCache::addPlayCallback(const std::function<void()> &callback) {
|
||||
std::lock_guard<std::mutex> lk(_playCallbackMutex);
|
||||
switch (_state) {
|
||||
switch (_state.load()) {
|
||||
case State::INITIAL:
|
||||
case State::LOADING:
|
||||
_playCallbacks.push_back(callback);
|
||||
@@ -296,7 +295,7 @@ void AudioCache::addPlayCallback(const std::function<void()> &callback) {
|
||||
break;
|
||||
|
||||
default:
|
||||
ALOGE("Invalid state: %d", _state);
|
||||
ALOGE("Invalid state: %d", static_cast<int>(_state.load()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -312,7 +311,7 @@ void AudioCache::invokingPlayCallbacks() {
|
||||
}
|
||||
|
||||
void AudioCache::addLoadCallback(const std::function<void(bool)> &callback) {
|
||||
switch (_state) {
|
||||
switch (_state.load()) {
|
||||
case State::INITIAL:
|
||||
case State::LOADING:
|
||||
_loadCallbacks.push_back(callback);
|
||||
@@ -326,7 +325,7 @@ void AudioCache::addLoadCallback(const std::function<void(bool)> &callback) {
|
||||
break;
|
||||
|
||||
default:
|
||||
ALOGE("Invalid state: %d", _state);
|
||||
ALOGE("Invalid state: %d", static_cast<int>(_state.load()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -337,18 +336,27 @@ void AudioCache::invokingLoadCallbacks() {
|
||||
return;
|
||||
}
|
||||
|
||||
auto scheduler = _scheduler.lock();
|
||||
if (!scheduler) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto isDestroyed = _isDestroyed;
|
||||
auto scheduler = CC_CURRENT_ENGINE()->getScheduler();
|
||||
scheduler->performFunctionInCocosThread([&, isDestroyed]() {
|
||||
const bool isReady = _state.load() == State::READY;
|
||||
scheduler->performFunctionInCocosThread([this, isDestroyed, isReady]() {
|
||||
if (*isDestroyed) {
|
||||
ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this);
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto &&cb : _loadCallbacks) {
|
||||
cb(_state == State::READY);
|
||||
// A callback may uncache this file or end the audio engine. Do not access the
|
||||
// cache again after invoking user code, and cancel any remaining callbacks.
|
||||
auto callbacks = std::move(_loadCallbacks);
|
||||
for (auto &&cb : callbacks) {
|
||||
if (*isDestroyed) {
|
||||
break;
|
||||
}
|
||||
cb(isReady);
|
||||
}
|
||||
|
||||
_loadCallbacks.clear();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -167,6 +167,13 @@ AudioEngineImpl::~AudioEngineImpl() {
|
||||
sche->unschedule("AudioEngine", this);
|
||||
}
|
||||
|
||||
// AudioEngine::end() has joined the worker pool before deleting this backend.
|
||||
// Queued tasks are discarded by the pool, so their caches will never receive
|
||||
// a read/skip notification from a worker. Unblock those cache destructors.
|
||||
for (auto &entry : _audioCaches) {
|
||||
entry.second.setSkipReadDataTask(true);
|
||||
}
|
||||
|
||||
if (s_ALContext) {
|
||||
alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
|
||||
|
||||
@@ -286,6 +293,7 @@ AudioCache *AudioEngineImpl::preload(const ccstd::string &filePath, std::functio
|
||||
auto it = _audioCaches.find(filePath);
|
||||
if (it == _audioCaches.end()) {
|
||||
audioCache = &_audioCaches[filePath];
|
||||
audioCache->_scheduler = _scheduler;
|
||||
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
|
||||
unsigned int cacheId = audioCache->_id;
|
||||
auto isCacheDestroyed = audioCache->_isDestroyed;
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
#include "audio/common/decoder/AudioDecoder.h"
|
||||
#include "base/Log.h"
|
||||
#include "base/Utils.h"
|
||||
@@ -500,6 +501,7 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void(in
|
||||
}
|
||||
|
||||
void AudioEngineImpl::update(float /*dt*/) {
|
||||
ccstd::vector<std::function<void()>> finishCallbacks;
|
||||
ALint sourceState;
|
||||
int audioID;
|
||||
AudioPlayer *player;
|
||||
@@ -534,7 +536,9 @@ void AudioEngineImpl::update(float /*dt*/) {
|
||||
_threadMutex.unlock();
|
||||
|
||||
if (player->_finishCallbak) {
|
||||
player->_finishCallbak(audioID, filePath); //IDEA: callback will delay 50ms
|
||||
finishCallbacks.emplace_back([callback = std::move(player->_finishCallbak), audioID, filePath]() {
|
||||
callback(audioID, filePath);
|
||||
});
|
||||
}
|
||||
delete player;
|
||||
_alSourceUsed[alSource] = false;
|
||||
@@ -549,6 +553,12 @@ void AudioEngineImpl::update(float /*dt*/) {
|
||||
sche->unschedule("AudioEngine", this);
|
||||
}
|
||||
}
|
||||
|
||||
// Callbacks may play/stop audio or destroy the engine. Finish all access to
|
||||
// player state before invoking them, and keep the callbacks in local storage.
|
||||
for (const auto &callback : finishCallbacks) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngineImpl::uncache(const ccstd::string &filePath) {
|
||||
|
||||
@@ -157,6 +157,7 @@ void Scheduler::schedule(const ccSchedulerFunc &callback, void *target, float in
|
||||
if (iter == _hashForTimers.end()) {
|
||||
element = ccnew HashTimerEntry();
|
||||
element->target = target;
|
||||
element->generation = ++_nextTimerGeneration;
|
||||
|
||||
_hashForTimers[target] = element;
|
||||
|
||||
@@ -368,10 +369,23 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() {
|
||||
void Scheduler::update(float dt) {
|
||||
_updateHashLocked = true;
|
||||
|
||||
// Iterate over all the custom selectors
|
||||
HashTimerEntry *elt = nullptr;
|
||||
for (auto iter = _hashForTimers.begin(); iter != _hashForTimers.end();) {
|
||||
elt = iter->second;
|
||||
// Callbacks can rehash the map or remove and recreate a target. Snapshot
|
||||
// identities, not iterators or entry pointers; new entries start next frame.
|
||||
struct TimerIdentity {
|
||||
void *target;
|
||||
uint64_t generation;
|
||||
};
|
||||
ccstd::vector<TimerIdentity> targets;
|
||||
targets.reserve(_hashForTimers.size());
|
||||
for (const auto &entry : _hashForTimers) {
|
||||
targets.push_back({entry.first, entry.second->generation});
|
||||
}
|
||||
for (const auto &target : targets) {
|
||||
auto iter = _hashForTimers.find(target.target);
|
||||
if (iter == _hashForTimers.end() || iter->second->generation != target.generation) {
|
||||
continue;
|
||||
}
|
||||
auto *elt = iter->second;
|
||||
_currentTarget = elt;
|
||||
_currentTargetSalvaged = false;
|
||||
|
||||
@@ -396,14 +410,9 @@ void Scheduler::update(float dt) {
|
||||
|
||||
// only delete currentTarget if no actions were scheduled during the cycle (issue #481)
|
||||
if (_currentTargetSalvaged && _currentTarget->timers.empty()) {
|
||||
++iter;
|
||||
removeHashElement(_currentTarget);
|
||||
if (iter != _hashForTimers.end()) {
|
||||
++iter;
|
||||
}
|
||||
} else {
|
||||
++iter;
|
||||
}
|
||||
_currentTarget = nullptr;
|
||||
}
|
||||
|
||||
_updateHashLocked = false;
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
|
||||
@@ -278,6 +279,7 @@ private:
|
||||
struct HashTimerEntry {
|
||||
ccstd::vector<Timer *> timers;
|
||||
void *target;
|
||||
uint64_t generation;
|
||||
int timerIndex;
|
||||
Timer *currentTimer;
|
||||
bool currentTimerSalvaged;
|
||||
@@ -291,9 +293,10 @@ private:
|
||||
|
||||
// Used for "selectors with interval"
|
||||
ccstd::unordered_map<void *, HashTimerEntry *> _hashForTimers;
|
||||
uint64_t _nextTimerGeneration = 0;
|
||||
struct HashTimerEntry *_currentTarget = nullptr;
|
||||
bool _currentTargetSalvaged = false;
|
||||
// If true unschedule will not remove anything from a hash. Elements will only be marked for deletion.
|
||||
// True while timer entries are being updated.
|
||||
bool _updateHashLocked = false;
|
||||
|
||||
// Used for "perform Function"
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
#include <bitset>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include "base/Macros.h"
|
||||
#include "base/TypeDef.h"
|
||||
@@ -145,10 +146,27 @@ CC_FORCE_INLINE Tgt bit_cast(const Src &src) { // NOLINT(readability-identifier-
|
||||
Tgt tgt;
|
||||
// Load src into registers first. This allows the memcpy to be elided by CUDA.
|
||||
const Src staged = src;
|
||||
memcpy(&tgt, &staged, sizeof(Tgt));
|
||||
std::memcpy(&tgt, &staged, sizeof(Tgt));
|
||||
return tgt;
|
||||
}
|
||||
|
||||
// Map a float to a uint32 whose unsigned-integer ordering matches the float's
|
||||
// numeric ordering (the classic radix-sort "flip"):
|
||||
// * non-negative: flip the sign bit
|
||||
// * negative: complement all bits
|
||||
// This maps [-inf, -0.0] to [0, 2^31) and [+0.0, +inf] to [2^31, 2^32), so the
|
||||
// unsigned comparison orders floats correctly. NaN must be excluded by the caller.
|
||||
//
|
||||
// Requires IEEE 754 binary32 (32-bit) floats, which every Cocos platform has.
|
||||
static_assert(sizeof(float) == sizeof(uint32_t), "float must be 32-bit");
|
||||
static_assert(std::numeric_limits<float>::is_iec559, "float must be IEEE 754");
|
||||
|
||||
CC_FORCE_INLINE uint32_t floatToSortableUint(float value) {
|
||||
constexpr uint32_t signBit = 0x80000000U;
|
||||
const auto bits = bit_cast<uint32_t>(value);
|
||||
return (bits & signBit) ? ~bits : (bits ^ signBit);
|
||||
}
|
||||
|
||||
} // namespace numext
|
||||
|
||||
// Following the Arm ACLE arm_neon.h should also include arm_fp16.h but not all
|
||||
@@ -164,7 +182,7 @@ struct HalfRaw {
|
||||
#if defined(CC_HAS_ARM64_FP16_SCALAR_ARITHMETIC)
|
||||
explicit HalfRaw(uint16_t raw) : x(numext::bit_cast<__fp16>(raw)) {
|
||||
}
|
||||
__fp16 x;
|
||||
__fp16 x; // NOLINT(modernize-use-default-member-init)
|
||||
#else
|
||||
explicit constexpr HalfRaw(uint16_t raw) : x(raw) {}
|
||||
uint16_t x; // NOLINT(modernize-use-default-member-init)
|
||||
|
||||
@@ -1184,10 +1184,12 @@ void ScriptEngine::removeUnhandledPromise(v8::Local<v8::Promise> promise) {
|
||||
// Remove handled promises from the list
|
||||
SE_ASSERT(promise->GetIsolate() == _isolate, "Wrong isolate");
|
||||
auto *isolate = promise->GetIsolate();
|
||||
for (auto it = _unhandledPromises.begin(); it != _unhandledPromises.end(); ++it) {
|
||||
for (auto it = _unhandledPromises.begin(); it != _unhandledPromises.end();) {
|
||||
v8::Local<v8::Promise> const unhandledPromise = std::get<0>(*it).Get(isolate);
|
||||
if (unhandledPromise == promise) {
|
||||
_unhandledPromises.erase(it--);
|
||||
it = _unhandledPromises.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,4 +30,4 @@ THE SOFTWARE.
|
||||
#define COCOS_VERSION_DEFINED 1
|
||||
#define COCOS_VERSION 40000
|
||||
|
||||
// #define COCOS_PRE_RELEASE "alpha"
|
||||
// #define COCOS_PRE_RELEASE "beta"
|
||||
|
||||
@@ -23,15 +23,34 @@
|
||||
****************************************************************************/
|
||||
|
||||
#include "core/assets/RenderTexture.h"
|
||||
#include "base/std/optional.h"
|
||||
#include "core/Root.h"
|
||||
#include "core/platform/Debug.h"
|
||||
#include "core/utils/IDGenerator.h"
|
||||
#include "renderer/gfx-base/GFXDef-common.h"
|
||||
#include "renderer/gfx-base/GFXDevice.h"
|
||||
#include "scene/RenderWindow.h"
|
||||
|
||||
namespace cc {
|
||||
|
||||
namespace {
|
||||
// The legacy limit used only when the GPU capability is unavailable,
|
||||
// e.g. when assets are loaded before the renderer is initialized.
|
||||
constexpr uint32_t FALLBACK_MAX_RENDER_TEXTURE_SIZE = 2048;
|
||||
|
||||
// Returns ccstd::nullopt when the device or its max texture size is unavailable.
|
||||
ccstd::optional<uint32_t> getMaxRenderTextureSize() {
|
||||
auto *device = gfx::Device::getInstance();
|
||||
if (device == nullptr) {
|
||||
return ccstd::nullopt;
|
||||
}
|
||||
const uint32_t maxTextureSize = device->getCapabilities().maxTextureSize;
|
||||
if (maxTextureSize == 0) {
|
||||
return ccstd::nullopt;
|
||||
}
|
||||
return maxTextureSize;
|
||||
}
|
||||
|
||||
gfx::RenderPassInfo getDefaultRenderPassInfo(gfx::Device *device) {
|
||||
gfx::RenderPassInfo info;
|
||||
info.colorAttachments.push_back({
|
||||
@@ -72,8 +91,11 @@ bool RenderTexture::destroy() {
|
||||
}
|
||||
|
||||
void RenderTexture::resize(uint32_t width, uint32_t height) {
|
||||
_width = std::floor(clampf(static_cast<float>(width), 1.F, 2048.F));
|
||||
_height = std::floor(clampf(static_cast<float>(height), 1.F, 2048.F));
|
||||
const auto maxTextureSize = getMaxRenderTextureSize();
|
||||
const auto maxSize = static_cast<float>(
|
||||
maxTextureSize.has_value() ? maxTextureSize.value() : FALLBACK_MAX_RENDER_TEXTURE_SIZE);
|
||||
_width = static_cast<uint32_t>(std::floor(clampf(static_cast<float>(width), 1.F, maxSize)));
|
||||
_height = static_cast<uint32_t>(std::floor(clampf(static_cast<float>(height), 1.F, maxSize)));
|
||||
if (_window != nullptr) {
|
||||
_window->resize(_width, _height);
|
||||
}
|
||||
@@ -146,7 +168,15 @@ void RenderTexture::initDefault(const ccstd::optional<ccstd::string> &uuid) {
|
||||
}
|
||||
|
||||
bool RenderTexture::validate() const {
|
||||
return _width >= 1 && _width <= 2048 && _height >= 1 && _height <= 2048;
|
||||
if (_width == 0 || _height == 0) {
|
||||
return false;
|
||||
}
|
||||
const auto maxTextureSize = getMaxRenderTextureSize();
|
||||
if (!maxTextureSize.has_value()) {
|
||||
return true;
|
||||
}
|
||||
const uint32_t maxSize = maxTextureSize.value();
|
||||
return _width <= maxSize && _height <= maxSize;
|
||||
}
|
||||
|
||||
ccstd::vector<uint8_t> RenderTexture::readPixels(uint32_t x, uint32_t y, uint32_t width, uint32_t height) const {
|
||||
|
||||
@@ -73,8 +73,9 @@ public:
|
||||
/**
|
||||
* @en Resize the render texture
|
||||
* @zh 修改渲染贴图的尺寸
|
||||
* @param width The pixel width, the range is from 1 to 2048
|
||||
* @param height The pixel height, the range is from 1 to 2048
|
||||
* The upper bound is the GPU max texture size. If the limit is unavailable, 2048 is used as a fallback.
|
||||
* @param width The pixel width, the range is from 1 to the maximum texture size supported by the GPU
|
||||
* @param height The pixel height, the range is from 1 to the maximum texture size supported by the GPU
|
||||
*/
|
||||
void resize(uint32_t width, uint32_t height);
|
||||
|
||||
|
||||
@@ -436,6 +436,9 @@ ccstd::unordered_map<uint32_t, ccstd::string> debugInfos = {
|
||||
{ 9101, "The length of the TypedArrayBuffer must be an integer." },
|
||||
{ 9201, "Cannot access game frame or container." },
|
||||
{ 9202, "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, "The current buffer beyond the limit in ui static component, please reduce the amount" },
|
||||
{ 9301, "The UI has not been initialized" },
|
||||
{ 9302, "Can't getGFXSampler with out device" },
|
||||
@@ -624,6 +627,23 @@ ccstd::unordered_map<uint32_t, ccstd::string> debugInfos = {
|
||||
{ 16418, "Debug bones or slots is invalid in cached mode." },
|
||||
{ 16419, "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)." },
|
||||
|
||||
};
|
||||
}//namespace cc
|
||||
|
||||
@@ -751,7 +751,19 @@ void SpineSkeletonInstance::resizeSlotRegion(const spine::String &slotName, uint
|
||||
releaseSlotCacheInfo(cacheInfo);
|
||||
}
|
||||
_slotTextureSet.put(slot, info);
|
||||
|
||||
auto &bones = _skeleton->getBones();
|
||||
const size_t boneCount = bones.size();
|
||||
std::vector<bool> activeBackup(boneCount);
|
||||
for (size_t i = 0; i < boneCount; ++i) {
|
||||
activeBackup[i] = bones[i]->isActive();
|
||||
}
|
||||
|
||||
_skeleton->updateCache();
|
||||
|
||||
for (size_t i = 0; i < boneCount; ++i) {
|
||||
bones[i]->setActive(activeBackup[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void SpineSkeletonInstance::setSlotTexture(const spine::String &slotName, const spine::String& textureUuid) {
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#include "platform/interfaces/modules/canvas/CanvasFont.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
#include <regex>
|
||||
#include <string_view>
|
||||
|
||||
namespace cc::detail {
|
||||
namespace {
|
||||
|
||||
bool isSpace(char c) {
|
||||
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
|
||||
}
|
||||
|
||||
bool isNewline(char c) {
|
||||
return c == '\n' || c == '\r' || c == '\f';
|
||||
}
|
||||
|
||||
void skipSpace(std::string_view input, size_t &pos) {
|
||||
while (pos < input.size() && isSpace(input[pos])) ++pos;
|
||||
}
|
||||
|
||||
int hexValue(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void appendCodePoint(std::string &output, uint32_t code) {
|
||||
if (code == 0 || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF)) code = 0xFFFD;
|
||||
if (code < 0x80) {
|
||||
output += static_cast<char>(code);
|
||||
} else if (code < 0x800) {
|
||||
output += static_cast<char>(0xC0 | (code >> 6));
|
||||
output += static_cast<char>(0x80 | (code & 0x3F));
|
||||
} else if (code < 0x10000) {
|
||||
output += static_cast<char>(0xE0 | (code >> 12));
|
||||
output += static_cast<char>(0x80 | ((code >> 6) & 0x3F));
|
||||
output += static_cast<char>(0x80 | (code & 0x3F));
|
||||
} else {
|
||||
output += static_cast<char>(0xF0 | (code >> 18));
|
||||
output += static_cast<char>(0x80 | ((code >> 12) & 0x3F));
|
||||
output += static_cast<char>(0x80 | ((code >> 6) & 0x3F));
|
||||
output += static_cast<char>(0x80 | (code & 0x3F));
|
||||
}
|
||||
}
|
||||
|
||||
// https://www.w3.org/TR/css-syntax-3/#consume-an-escaped-code-point
|
||||
bool readEscape(std::string_view input, size_t &pos, bool quoted, std::string &output) {
|
||||
if (++pos == input.size()) return false;
|
||||
if (isNewline(input[pos])) {
|
||||
if (!quoted) return false;
|
||||
if (input[pos++] == '\r' && pos < input.size() && input[pos] == '\n') ++pos;
|
||||
return true;
|
||||
}
|
||||
if (hexValue(input[pos]) >= 0) {
|
||||
uint32_t code = 0;
|
||||
for (int digits = 0; digits < 6 && pos < input.size() && hexValue(input[pos]) >= 0; ++digits) {
|
||||
code = code * 16 + static_cast<uint32_t>(hexValue(input[pos++]));
|
||||
}
|
||||
if (pos < input.size() && isSpace(input[pos])) {
|
||||
if (input[pos++] == '\r' && pos < input.size() && input[pos] == '\n') ++pos;
|
||||
}
|
||||
appendCodePoint(output, code);
|
||||
} else if (input[pos] == '\0') {
|
||||
appendCodePoint(output, 0);
|
||||
++pos;
|
||||
} else {
|
||||
output += input[pos++];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool decodeQuotedFamily(std::string_view input, std::string &family) {
|
||||
size_t pos = 0;
|
||||
skipSpace(input, pos);
|
||||
if (pos == input.size() || (input[pos] != '"' && input[pos] != '\'')) return false;
|
||||
const char quote = input[pos++];
|
||||
while (pos < input.size()) {
|
||||
const char c = input[pos];
|
||||
if (c == quote) {
|
||||
++pos;
|
||||
skipSpace(input, pos);
|
||||
return pos == input.size() && !family.empty();
|
||||
}
|
||||
if (isNewline(c)) return false;
|
||||
if (c == '\\') {
|
||||
if (!readEscape(input, pos, true, family)) return false;
|
||||
} else if (c == '\0') {
|
||||
appendCodePoint(family, 0);
|
||||
++pos;
|
||||
} else {
|
||||
family += c;
|
||||
++pos;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
static CanvasFont parseLegacyCanvasFont(const std::string &font) {
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
|
||||
std::string boldStr;
|
||||
std::string fontName = "Arial";
|
||||
std::string fontSizeStr = "30";
|
||||
|
||||
std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))");
|
||||
std::match_results<std::string::const_iterator> results;
|
||||
if (std::regex_search(font.cbegin(), font.cend(), results, re)) {
|
||||
fontSizeStr = results[2].str();
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
// support get font name contain space,example `times new roman`
|
||||
// if regex rule that does not conform to the rules,such as Chinese,it defaults to Arial
|
||||
std::match_results<std::string::const_iterator> fontResults;
|
||||
std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))");
|
||||
std::string tmp(results[4].str());
|
||||
if (std::regex_match(tmp, fontResults, fontRe)) {
|
||||
fontName = results[4].str();
|
||||
}
|
||||
}
|
||||
|
||||
auto fontSize = static_cast<float>(atof(fontSizeStr.c_str()));
|
||||
bool isBold = !boldStr.empty() || font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos;
|
||||
bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos;
|
||||
return {fontName, static_cast<float>(fontSize), isBold, isItalic, false, false};
|
||||
#elif CC_PLATFORM == CC_PLATFORM_QNX
|
||||
|
||||
std::string boldStr;
|
||||
std::string fontName = "Arial";
|
||||
std::string fontSizeStr = "30";
|
||||
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)");
|
||||
std::match_results<std::string::const_iterator> results;
|
||||
if (std::regex_search(font.cbegin(), font.cend(), results, re)) {
|
||||
boldStr = results[1].str();
|
||||
fontSizeStr = results[2].str();
|
||||
fontName = results[5].str();
|
||||
}
|
||||
bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos;
|
||||
auto fontSize = static_cast<float>(atof(fontSizeStr.c_str()));
|
||||
bool isBold = !boldStr.empty() || font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos;
|
||||
// SE_LOGD("CanvasRenderingContext2D::setfont: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold);
|
||||
return {fontName, fontSize, isBold, isItalic, false, false};
|
||||
#elif CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
|
||||
std::string fontName = "sans-serif";
|
||||
std::string fontSizeStr = "30";
|
||||
std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))");
|
||||
std::match_results<std::string::const_iterator> results;
|
||||
if (std::regex_search(font.cbegin(), font.cend(), results, re)) {
|
||||
fontSizeStr = results[2].str();
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
// support get font name contain space,example `times new roman`
|
||||
// if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif
|
||||
std::match_results<std::string::const_iterator> fontResults;
|
||||
std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))");
|
||||
std::string tmp(results[4].str());
|
||||
if (std::regex_match(tmp, fontResults, fontRe)) {
|
||||
// fontName = results[4].str();
|
||||
}
|
||||
}
|
||||
|
||||
bool isBold = font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos;
|
||||
bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos;
|
||||
float fontSize = static_cast<float>(atof(fontSizeStr.c_str()));
|
||||
// SE_LOGD("CanvasRenderingContext2D::setfont: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold);
|
||||
return {fontName, fontSize, isBold, isItalic, false, false};
|
||||
#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY
|
||||
std::string fontName = "sans-serif";
|
||||
std::string fontSizeStr = "30";
|
||||
std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))");
|
||||
std::match_results<std::string::const_iterator> results;
|
||||
if (std::regex_search(font.cbegin(), font.cend(), results, re)) {
|
||||
fontSizeStr = results[2].str();
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
// support get font name contain space,example `times new roman`
|
||||
// if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif
|
||||
std::match_results<std::string::const_iterator> fontResults;
|
||||
std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))");
|
||||
std::string tmp(results[4].str());
|
||||
if (std::regex_match(tmp, fontResults, fontRe)) {
|
||||
fontName = results[4].str();
|
||||
}
|
||||
}
|
||||
|
||||
double fontSize = atof(fontSizeStr.c_str());
|
||||
bool isBold = font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos;
|
||||
bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos;
|
||||
bool isSmallCaps = font.find("small-caps", 0) != std::string::npos || font.find("Small-Caps") != std::string::npos;
|
||||
bool isOblique = font.find("oblique", 0) != std::string::npos || font.find("Oblique", 0) != std::string::npos;
|
||||
// font-style: italic, oblique, normal
|
||||
// font-weight: normal, bold
|
||||
// font-variant: normal, small-caps
|
||||
return {fontName, static_cast<float>(fontSize), isBold, isItalic, isOblique, isSmallCaps};
|
||||
#elif CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS
|
||||
|
||||
std::string boldStr;
|
||||
std::string fontName = "Arial";
|
||||
std::string fontSizeStr = "30";
|
||||
bool isItalic = font.find("italic", 0) != std::string::npos || font.find("Italic", 0) != std::string::npos;
|
||||
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)");
|
||||
std::match_results<std::string::const_iterator> results;
|
||||
if (std::regex_search(font.cbegin(), font.cend(), results, re)) {
|
||||
boldStr = results[1].str();
|
||||
fontSizeStr = results[2].str();
|
||||
fontName = results[5].str();
|
||||
}
|
||||
float fontSize = atof(fontSizeStr.c_str());
|
||||
bool isBold = !boldStr.empty() || font.find("bold", 0) != std::string::npos || font.find("Bold", 0) != std::string::npos;
|
||||
return {fontName, static_cast<float>(fontSize), isBold, isItalic, false, false};
|
||||
#endif
|
||||
return {};
|
||||
}
|
||||
|
||||
CanvasFont parseCanvasFont(const std::string &font) {
|
||||
static const std::regex DESCRIPTION(R"(\s*((\d+)([\.]\d+)?)px\s+([\s\S]*))");
|
||||
std::smatch match;
|
||||
std::string family;
|
||||
if (!std::regex_search(font, match, DESCRIPTION) || !decodeQuotedFamily(match[4].str(), family)) {
|
||||
return parseLegacyCanvasFont(font);
|
||||
}
|
||||
|
||||
// Recover the descriptor used before TS serialized the asset's registered alias.
|
||||
// Use it only when the old platform parser recognizes that complete alias;
|
||||
// partial matches and unsupported names keep the original fallback behavior.
|
||||
const auto legacyDescription = font.substr(0, static_cast<size_t>(match.position(4))) + family;
|
||||
auto compatible = parseLegacyCanvasFont(legacyDescription);
|
||||
if (compatible.family == family) {
|
||||
return compatible;
|
||||
}
|
||||
auto fallback = parseLegacyCanvasFont(font);
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
// These platforms used to lose the size when the family was rejected.
|
||||
// Recover it only for complete quoted families with an engine-supported
|
||||
// style prefix. Keep the fallback family and existing style flags intact.
|
||||
static const std::regex STYLE_PREFIX(R"(\s*(?:(?:normal|bold|italic|oblique|small-caps)\s+)*)", std::regex::icase);
|
||||
if (std::regex_match(font.cbegin(), font.cbegin() + match.position(1), STYLE_PREFIX)) {
|
||||
const auto size = static_cast<float>(atof(match[1].str().c_str()));
|
||||
// Native backends may narrow sizes to int. Do not recover unsafe values.
|
||||
if (std::isfinite(size) && size >= 0.F && static_cast<double>(size) <= std::numeric_limits<int>::max()) {
|
||||
fallback.size = size;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return fallback;
|
||||
}
|
||||
|
||||
} // namespace cc::detail
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include "base/Macros.h"
|
||||
|
||||
namespace cc::detail {
|
||||
|
||||
struct CanvasFont {
|
||||
std::string family;
|
||||
float size{0.F};
|
||||
bool bold{false};
|
||||
bool italic{false};
|
||||
bool oblique{false};
|
||||
bool smallCaps{false};
|
||||
};
|
||||
|
||||
// Internal native Canvas parsing, including the existing per-platform fallbacks.
|
||||
// Family interpretation must not depend on the font registry. Callers serialize raw
|
||||
// asset aliases once as CSS strings, including any literal quotes in the alias.
|
||||
CC_DLL CanvasFont parseCanvasFont(const std::string &font);
|
||||
|
||||
} // namespace cc::detail
|
||||
@@ -25,12 +25,12 @@
|
||||
#include "platform/interfaces/modules/canvas/CanvasRenderingContext2D.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <regex>
|
||||
#include "base/csscolorparser.h"
|
||||
#include "cocos/bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/bindings/manual/jsb_platform.h"
|
||||
#include "math/Math.h"
|
||||
#include "platform/FileUtils.h"
|
||||
#include "platform/interfaces/modules/canvas/CanvasFont.h"
|
||||
|
||||
#if defined(CC_SERVER_MODE)
|
||||
#include "platform/empty/modules/CanvasRenderingContext2DDelegate.h"
|
||||
@@ -218,133 +218,11 @@ void CanvasRenderingContext2D::rect(float x, float y, float w, float h) {
|
||||
|
||||
void CanvasRenderingContext2D::setFont(const ccstd::string &font) {
|
||||
recreateBufferIfNeeded();
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_QNX || CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY || CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS
|
||||
if (_font != font) {
|
||||
_font = font;
|
||||
|
||||
ccstd::string boldStr;
|
||||
ccstd::string fontName = "Arial";
|
||||
ccstd::string fontSizeStr = "30";
|
||||
|
||||
std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))");
|
||||
std::match_results<ccstd::string::const_iterator> results;
|
||||
if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) {
|
||||
fontSizeStr = results[2].str();
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
// support get font name contain space,example `times new roman`
|
||||
// if regex rule that does not conform to the rules,such as Chinese,it defaults to Arial
|
||||
std::match_results<ccstd::string::const_iterator> fontResults;
|
||||
std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))");
|
||||
ccstd::string tmp(results[4].str());
|
||||
if (std::regex_match(tmp, fontResults, fontRe)) {
|
||||
fontName = results[4].str();
|
||||
}
|
||||
}
|
||||
|
||||
auto fontSize = static_cast<float>(atof(fontSizeStr.c_str()));
|
||||
bool isBold = !boldStr.empty() || font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos;
|
||||
bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos;
|
||||
_delegate->updateFont(fontName, static_cast<float>(fontSize), isBold, isItalic, false, false);
|
||||
}
|
||||
#elif CC_PLATFORM == CC_PLATFORM_QNX
|
||||
if (_font != font) {
|
||||
_font = font;
|
||||
|
||||
ccstd::string boldStr;
|
||||
ccstd::string fontName = "Arial";
|
||||
ccstd::string fontSizeStr = "30";
|
||||
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)");
|
||||
std::match_results<ccstd::string::const_iterator> results;
|
||||
if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) {
|
||||
boldStr = results[1].str();
|
||||
fontSizeStr = results[2].str();
|
||||
fontName = results[5].str();
|
||||
}
|
||||
bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos;
|
||||
auto fontSize = static_cast<float>(atof(fontSizeStr.c_str()));
|
||||
bool isBold = !boldStr.empty() || font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos;
|
||||
//SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold);
|
||||
_delegate->updateFont(fontName, fontSize, isBold, isItalic, false, false);
|
||||
}
|
||||
#elif CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
if (_font != font) {
|
||||
_font = font;
|
||||
|
||||
ccstd::string fontName = "sans-serif";
|
||||
ccstd::string fontSizeStr = "30";
|
||||
std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))");
|
||||
std::match_results<ccstd::string::const_iterator> results;
|
||||
if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) {
|
||||
fontSizeStr = results[2].str();
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
// support get font name contain space,example `times new roman`
|
||||
// if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif
|
||||
std::match_results<ccstd::string::const_iterator> fontResults;
|
||||
std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))");
|
||||
ccstd::string tmp(results[4].str());
|
||||
if (std::regex_match(tmp, fontResults, fontRe)) {
|
||||
//fontName = results[4].str();
|
||||
}
|
||||
}
|
||||
|
||||
bool isBold = font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos;
|
||||
bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos;
|
||||
float fontSize = static_cast<float>(atof(fontSizeStr.c_str()));
|
||||
//SE_LOGD("CanvasRenderingContext2D::set_font: %s, Size: %f, isBold: %b\n", fontName.c_str(), fontSize, isBold);
|
||||
_delegate->updateFont(fontName, fontSize, isBold, isItalic, false, false);
|
||||
}
|
||||
#elif CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY
|
||||
if (_font != font) {
|
||||
_font = font;
|
||||
ccstd::string fontName = "sans-serif";
|
||||
ccstd::string fontSizeStr = "30";
|
||||
std::regex re(R"(\s*((\d+)([\.]\d+)?)px\s+([^\r\n]*))");
|
||||
std::match_results<ccstd::string::const_iterator> results;
|
||||
if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) {
|
||||
fontSizeStr = results[2].str();
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
// support get font name contain space,example `times new roman`
|
||||
// if regex rule that does not conform to the rules,such as Chinese,it defaults to sans-serif
|
||||
std::match_results<ccstd::string::const_iterator> fontResults;
|
||||
std::regex fontRe(R"(([\w\s-]+|"[\w\s-]+"$))");
|
||||
ccstd::string tmp(results[4].str());
|
||||
if (std::regex_match(tmp, fontResults, fontRe)) {
|
||||
fontName = results[4].str();
|
||||
}
|
||||
}
|
||||
|
||||
double fontSize = atof(fontSizeStr.c_str());
|
||||
bool isBold = font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos;
|
||||
bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos;
|
||||
bool isSmallCaps = font.find("small-caps", 0) != ccstd::string::npos || font.find("Small-Caps") != ccstd::string::npos;
|
||||
bool isOblique = font.find("oblique", 0) != ccstd::string::npos || font.find("Oblique", 0) != ccstd::string::npos;
|
||||
//font-style: italic, oblique, normal
|
||||
//font-weight: normal, bold
|
||||
//font-variant: normal, small-caps
|
||||
_delegate->updateFont(fontName, static_cast<float>(fontSize), isBold, isItalic, isOblique, isSmallCaps);
|
||||
}
|
||||
#elif CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS
|
||||
if (_font != font) {
|
||||
_font = font;
|
||||
|
||||
ccstd::string boldStr;
|
||||
ccstd::string fontName = "Arial";
|
||||
ccstd::string fontSizeStr = "30";
|
||||
bool isItalic = font.find("italic", 0) != ccstd::string::npos || font.find("Italic", 0) != ccstd::string::npos;
|
||||
|
||||
// support get font name from `60px American` or `60px "American abc-abc_abc"`
|
||||
std::regex re("(bold)?\\s*((\\d+)([\\.]\\d+)?)px\\s+([\\w-]+|\"[\\w -]+\"$)");
|
||||
std::match_results<ccstd::string::const_iterator> results;
|
||||
if (std::regex_search(_font.cbegin(), _font.cend(), results, re)) {
|
||||
boldStr = results[1].str();
|
||||
fontSizeStr = results[2].str();
|
||||
fontName = results[5].str();
|
||||
}
|
||||
float fontSize = atof(fontSizeStr.c_str());
|
||||
bool isBold = !boldStr.empty() || font.find("bold", 0) != ccstd::string::npos || font.find("Bold", 0) != ccstd::string::npos;
|
||||
_delegate->updateFont(fontName, static_cast<float>(fontSize), isBold, isItalic, false, false);
|
||||
const auto parsed = detail::parseCanvasFont(font);
|
||||
_delegate->updateFont(parsed.family, parsed.size, parsed.bold, parsed.italic, parsed.oblique, parsed.smallCaps);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1007,7 +1007,8 @@ public:
|
||||
for (auto *set : sets) {
|
||||
set->update(oldView, newView);
|
||||
}
|
||||
_gpuBufferViewSet.erase(iter);
|
||||
// Connecting the new view may have rehashed the map.
|
||||
_gpuBufferViewSet.erase(oldView);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1018,7 +1019,8 @@ public:
|
||||
for (auto *set : sets) {
|
||||
set->update(oldView, newView);
|
||||
}
|
||||
_gpuTextureViewSet.erase(iter);
|
||||
// Connecting the new view may have rehashed the map.
|
||||
_gpuTextureViewSet.erase(oldView);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1217,7 +1219,8 @@ public:
|
||||
ia->update(oldBuffer, newBuffer);
|
||||
_ias[newBuffer].insert(ia);
|
||||
}
|
||||
_ias.erase(iter);
|
||||
// Registering the new buffer may have rehashed the map.
|
||||
_ias.erase(oldBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,15 @@ struct CC_DLL RenderPass {
|
||||
uint32_t hash = 0;
|
||||
float depth = 0.0F;
|
||||
uint32_t shaderID = 0;
|
||||
/**
|
||||
* Packed sort keys, computed once in RenderQueue::insertRenderPass so the
|
||||
* comparator degenerates to a single uint64 compare.
|
||||
* opaque: primaryKey = hash, secondaryKey = depthKey << 32 | shaderID
|
||||
* transparent: primaryKey = priority << 32 | hash, secondaryKey = ~depthKey << 32 | shaderID
|
||||
* depthKey is the order-preserving uint32 mapping of depth.
|
||||
*/
|
||||
uint64_t primaryKey = 0;
|
||||
uint64_t secondaryKey = 0;
|
||||
uint32_t passIndex = 0;
|
||||
const scene::SubModel *subModel = nullptr;
|
||||
};
|
||||
@@ -175,35 +184,17 @@ using RenderQueueDescList = ccstd::vector<IntrusivePtr<RenderQueueDesc>>;
|
||||
uint32_t getPhaseID(const ccstd::string &phase);
|
||||
|
||||
inline bool opaqueCompareFn(const RenderPass &a, const RenderPass &b) {
|
||||
if (a.hash != b.hash) {
|
||||
return a.hash < b.hash;
|
||||
if (a.primaryKey != b.primaryKey) {
|
||||
return a.primaryKey < b.primaryKey;
|
||||
}
|
||||
|
||||
CC_ASSERT(!std::isnan(a.depth) && !std::isnan(b.depth));
|
||||
|
||||
if (a.depth != b.depth) {
|
||||
return a.depth < b.depth;
|
||||
}
|
||||
|
||||
return a.shaderID < b.shaderID;
|
||||
return a.secondaryKey < b.secondaryKey;
|
||||
}
|
||||
|
||||
inline bool transparentCompareFn(const RenderPass &a, const RenderPass &b) {
|
||||
if (a.priority != b.priority) {
|
||||
return a.priority < b.priority;
|
||||
if (a.primaryKey != b.primaryKey) {
|
||||
return a.primaryKey < b.primaryKey;
|
||||
}
|
||||
|
||||
if (a.hash != b.hash) {
|
||||
return a.hash < b.hash;
|
||||
}
|
||||
|
||||
CC_ASSERT(!std::isnan(a.depth) && !std::isnan(b.depth));
|
||||
|
||||
if (a.depth != b.depth) {
|
||||
return b.depth < a.depth;
|
||||
}
|
||||
|
||||
return a.shaderID < b.shaderID;
|
||||
return a.secondaryKey < b.secondaryKey;
|
||||
}
|
||||
|
||||
inline uint32_t convertPhase(const ccstd::vector<ccstd::string> &stages) {
|
||||
@@ -688,6 +679,9 @@ static constexpr uint32_t CLUSTER_LIGHT_BINDING = 4;
|
||||
static constexpr uint32_t CLUSTER_LIGHT_INDEX_BINDING = 5;
|
||||
static constexpr uint32_t CLUSTER_LIGHT_GRID_BINDING = 6;
|
||||
|
||||
constexpr const char *GEOMETRY_RENDERER_COMMAND = "geometry-renderer";
|
||||
constexpr const char *DEBUG_RENDERER_COMMAND = "debug-renderer";
|
||||
|
||||
void localDescriptorSetLayoutResizeMaxJoints(uint32_t maxCount);
|
||||
|
||||
} // namespace pipeline
|
||||
|
||||
@@ -47,6 +47,34 @@
|
||||
namespace cc {
|
||||
namespace pipeline {
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
DebugRendererRenderCommand::DebugRendererRenderCommand(PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {
|
||||
}
|
||||
|
||||
void DebugRendererRenderCommand::beginRenderCommand(const RenderCommandContext &ctx) {
|
||||
renderDebugRenderer(ctx.renderPass, ctx.cmdBuff, _sceneData, ctx.camera);
|
||||
}
|
||||
|
||||
void DebugRendererRenderCommand::endRenderCommand(const RenderCommandContext & /*ctx*/) {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
GeometryRendererRenderCommand::GeometryRendererRenderCommand(PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {
|
||||
}
|
||||
|
||||
void GeometryRendererRenderCommand::beginRenderCommand(const RenderCommandContext &ctx) {
|
||||
if (ctx.camera && ctx.camera->getGeometryRenderer()) {
|
||||
ctx.camera->getGeometryRenderer()->render(ctx.renderPass, ctx.cmdBuff, _sceneData);
|
||||
}
|
||||
}
|
||||
|
||||
void GeometryRendererRenderCommand::endRenderCommand(const RenderCommandContext & /*ctx*/) {
|
||||
}
|
||||
#endif
|
||||
|
||||
framegraph::StringHandle RenderPipeline::fgStrHandleOutDepthTexture = framegraph::FrameGraph::stringToHandle("depthTexture");
|
||||
framegraph::StringHandle RenderPipeline::fgStrHandleOutColorTexture = framegraph::FrameGraph::stringToHandle("outputTexture");
|
||||
framegraph::StringHandle RenderPipeline::fgStrHandlePostprocessPass = framegraph::FrameGraph::stringToHandle("pipelinePostPass");
|
||||
@@ -87,6 +115,10 @@ bool RenderPipeline::activate(gfx::Swapchain * /*swapchain*/) {
|
||||
_pipelineSceneData->activate(_device);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
CC_DEBUG_RENDERER->activate(_device);
|
||||
addRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND, std::make_shared<DebugRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
addRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND, std::make_shared<GeometryRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
|
||||
// generate macros here rather than construct func because _clusterEnabled
|
||||
@@ -115,6 +147,15 @@ void RenderPipeline::onGlobalPipelineStateChanged() {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
void RenderPipeline::addRenderCommand(const ccstd::string &name, std::shared_ptr<RenderCommand> ptr) {
|
||||
_renderCommands[name] = std::move(ptr);
|
||||
}
|
||||
|
||||
RenderCommand *RenderPipeline::getRenderCommand(const ccstd::string &name) const {
|
||||
const auto iter = _renderCommands.find(name);
|
||||
return iter == _renderCommands.end() ? nullptr : iter->second.get();
|
||||
}
|
||||
|
||||
void RenderPipeline::destroyQuadInputAssembler() {
|
||||
CC_SAFE_DESTROY_AND_DELETE(_quadIB);
|
||||
|
||||
|
||||
@@ -34,11 +34,14 @@
|
||||
#include "renderer/core/PassUtils.h"
|
||||
#include "scene/Model.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace cc {
|
||||
namespace gfx {
|
||||
class CommandBuffer;
|
||||
class DescriptorSet;
|
||||
class DescriptorSetLayout;
|
||||
class RenderPass;
|
||||
} // namespace gfx
|
||||
namespace scene {
|
||||
class Camera;
|
||||
@@ -54,6 +57,53 @@ class PipelineSceneData;
|
||||
class GlobalDSManager;
|
||||
class RenderStage;
|
||||
class GeometryRenderer;
|
||||
|
||||
struct RenderCommandContext {
|
||||
gfx::RenderPass *renderPass{nullptr};
|
||||
gfx::CommandBuffer *cmdBuff{nullptr};
|
||||
PipelineSceneData *sceneData{nullptr};
|
||||
const scene::Camera *camera{nullptr};
|
||||
};
|
||||
|
||||
class RenderCommand {
|
||||
public:
|
||||
RenderCommand() noexcept = default;
|
||||
RenderCommand(RenderCommand &&rhs) = delete;
|
||||
RenderCommand(RenderCommand const &rhs) = delete;
|
||||
RenderCommand &operator=(RenderCommand &&rhs) = delete;
|
||||
RenderCommand &operator=(RenderCommand const &rhs) = delete;
|
||||
virtual ~RenderCommand() noexcept = default;
|
||||
|
||||
virtual void beginRenderCommand(const RenderCommandContext &ctx) = 0;
|
||||
virtual void endRenderCommand(const RenderCommandContext &ctx) = 0;
|
||||
};
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
class DebugRendererRenderCommand final : public RenderCommand {
|
||||
public:
|
||||
explicit DebugRendererRenderCommand(PipelineSceneData *sceneData);
|
||||
|
||||
void beginRenderCommand(const RenderCommandContext &ctx) override;
|
||||
void endRenderCommand(const RenderCommandContext &ctx) override;
|
||||
|
||||
private:
|
||||
PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
class GeometryRendererRenderCommand final : public RenderCommand {
|
||||
public:
|
||||
explicit GeometryRendererRenderCommand(PipelineSceneData *sceneData);
|
||||
|
||||
void beginRenderCommand(const RenderCommandContext &ctx) override;
|
||||
void endRenderCommand(const RenderCommandContext &ctx) override;
|
||||
|
||||
private:
|
||||
PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
#endif
|
||||
|
||||
struct CC_DLL RenderPipelineInfo {
|
||||
uint32_t tag = 0;
|
||||
RenderFlowList flows;
|
||||
@@ -140,6 +190,9 @@ public:
|
||||
#endif
|
||||
}
|
||||
|
||||
void addRenderCommand(const ccstd::string &name, std::shared_ptr<RenderCommand> ptr);
|
||||
RenderCommand *getRenderCommand(const ccstd::string &name) const;
|
||||
|
||||
inline void resetRenderQueue(bool reset) { _resetRenderQueue = reset; }
|
||||
inline bool isRenderQueueReset() const { return _resetRenderQueue; }
|
||||
|
||||
@@ -194,6 +247,7 @@ protected:
|
||||
ccstd::unordered_map<Vec4, gfx::InputAssembler *, Hasher<Vec4>> _quadIA;
|
||||
|
||||
framegraph::FrameGraph _fg;
|
||||
ccstd::unordered_map<ccstd::string, std::shared_ptr<RenderCommand>> _renderCommands;
|
||||
ccstd::unordered_map<gfx::ClearFlags, gfx::RenderPass *> _renderPasses;
|
||||
|
||||
// use cluster culling or not
|
||||
|
||||
@@ -24,10 +24,12 @@
|
||||
|
||||
#include "RenderQueue.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#include "PipelineSceneData.h"
|
||||
#include "PipelineStateManager.h"
|
||||
#include "RenderPipeline.h"
|
||||
#include "base/Utils.h"
|
||||
#include "gfx-base/GFXCommandBuffer.h"
|
||||
#include "gfx-base/GFXDevice.h"
|
||||
#include "gfx-base/GFXShader.h"
|
||||
@@ -60,7 +62,28 @@ bool RenderQueue::insertRenderPass(const RenderObject &renderObj, uint32_t subMo
|
||||
auto shaderId = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(subModel->getShader(passIdx)));
|
||||
const auto hash = (0 << 30) | (passPriority << 16) | (modelPriority << 8) | passIdx;
|
||||
const auto priority = renderObj.model->getPriority();
|
||||
RenderPass renderPass = {priority, hash, renderObj.depth, shaderId, passIdx, subModel};
|
||||
RenderPass renderPass{};
|
||||
renderPass.priority = priority;
|
||||
renderPass.hash = hash;
|
||||
renderPass.depth = renderObj.depth;
|
||||
renderPass.shaderID = shaderId;
|
||||
renderPass.passIndex = passIdx;
|
||||
renderPass.subModel = subModel;
|
||||
|
||||
/**
|
||||
* Pack the sort keys once here so the comparator only compares uint64 keys.
|
||||
* secondaryKey: depthKey << 32 | shaderID (transparent inverts depth for back-to-front).
|
||||
*/
|
||||
CC_ASSERT(!std::isnan(renderObj.depth));
|
||||
const uint32_t depthKey = utils::numext::floatToSortableUint(renderObj.depth);
|
||||
if (isTransparent) {
|
||||
const uint32_t invertedDepthKey = ~depthKey;
|
||||
renderPass.primaryKey = (static_cast<uint64_t>(priority) << 32) | hash;
|
||||
renderPass.secondaryKey = (static_cast<uint64_t>(invertedDepthKey) << 32) | shaderId;
|
||||
} else {
|
||||
renderPass.primaryKey = hash;
|
||||
renderPass.secondaryKey = (static_cast<uint64_t>(depthKey) << 32) | shaderId;
|
||||
}
|
||||
_queue.emplace_back(renderPass);
|
||||
|
||||
return true;
|
||||
|
||||
@@ -63,6 +63,7 @@ struct CustomRenderGraphContext {
|
||||
const RenderGraph* renderGraph{nullptr};
|
||||
const ResourceGraph* resourceGraph{nullptr};
|
||||
gfx::CommandBuffer* primaryCommandBuffer{nullptr};
|
||||
gfx::RenderPass* currentRenderPass{nullptr};
|
||||
};
|
||||
|
||||
class CustomRenderPass : public Customization {
|
||||
|
||||
@@ -44,12 +44,6 @@
|
||||
#include "details/GraphView.h"
|
||||
#include "details/GslUtils.h"
|
||||
#include "details/Range.h"
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
#include "cocos/renderer/pipeline/helper/Utils.h"
|
||||
#endif
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
#include "cocos/renderer/pipeline/GeometryRenderer.h"
|
||||
#endif
|
||||
|
||||
namespace cc {
|
||||
|
||||
@@ -704,10 +698,14 @@ struct RenderGraphVisitor : boost::dfs_visitor<> {
|
||||
ctx.cmdBuff, ctx.currentPass, ctx.subpassIndex, sceneData.flags);
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (any(sceneData.flags & SceneFlags::GEOMETRY) &&
|
||||
camera && camera->getGeometryRenderer()) {
|
||||
camera->getGeometryRenderer()->render(
|
||||
ctx.currentPass, ctx.cmdBuff, ctx.ppl->getPipelineSceneData());
|
||||
const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, sceneID);
|
||||
if (!renderData.custom.empty()) {
|
||||
const auto& commands = ctx.ppl->custom.renderCommands;
|
||||
auto iter = commands.find(renderData.custom);
|
||||
if (iter != commands.end()) {
|
||||
ctx.customContext.currentRenderPass = ctx.currentPass;
|
||||
iter->second->beginRenderCommand(ctx.customContext, sceneID);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -786,24 +784,18 @@ struct RenderGraphVisitor : boost::dfs_visitor<> {
|
||||
}
|
||||
|
||||
void begin(const Blit& blit, RenderGraph::vertex_descriptor vertID) const {
|
||||
tryBindPassDescriptorSet(vertID);
|
||||
tryBindQueueDescriptorSets(vertID);
|
||||
const auto& renderData = get(RenderGraph::DataTag{}, ctx.g, vertID);
|
||||
if (!renderData.custom.empty()) {
|
||||
const auto& commands = ctx.ppl->custom.renderCommands;
|
||||
auto iter = commands.find(renderData.custom);
|
||||
if (iter != commands.end()) {
|
||||
ctx.customContext.currentRenderPass = ctx.currentPass;
|
||||
iter->second->beginRenderCommand(ctx.customContext, vertID);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
if (blit.blitType == BlitType::DRAW_PROFILE) {
|
||||
auto* renderPass = ctx.currentPass;
|
||||
auto* cmdBuff = ctx.cmdBuff;
|
||||
renderDebugRenderer(renderPass, cmdBuff, ctx.ppl->getPipelineSceneData(), cc::pipeline::profilerCamera);
|
||||
}
|
||||
#endif
|
||||
tryBindPassDescriptorSet(vertID);
|
||||
tryBindQueueDescriptorSets(vertID);
|
||||
|
||||
switch (blit.blitType) {
|
||||
case BlitType::FULLSCREEN_QUAD:
|
||||
|
||||
@@ -48,6 +48,10 @@
|
||||
#include "profiler/DebugRenderer.h"
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
#include "cocos/renderer/pipeline/GeometryRenderer.h"
|
||||
#endif
|
||||
|
||||
namespace cc {
|
||||
|
||||
namespace render {
|
||||
@@ -106,6 +110,54 @@ void addSubresourceNode<gfx::Format::DEPTH_STENCIL>(ResourceGraph::vertex_descri
|
||||
|
||||
} // namespace
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
namespace {
|
||||
class DebugRendererRenderCommand final : public CustomRenderCommand {
|
||||
public:
|
||||
explicit DebugRendererRenderCommand(pipeline::PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {}
|
||||
|
||||
void beginRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
std::ignore = vertID;
|
||||
if (rg.currentRenderPass) {
|
||||
DebugRenderer::getInstance()->render(rg.currentRenderPass, rg.primaryCommandBuffer, _sceneData);
|
||||
}
|
||||
}
|
||||
|
||||
void endRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
std::ignore = rg;
|
||||
std::ignore = vertID;
|
||||
}
|
||||
|
||||
private:
|
||||
pipeline::PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
class GeometryRendererRenderCommand final : public CustomRenderCommand {
|
||||
public:
|
||||
explicit GeometryRendererRenderCommand(pipeline::PipelineSceneData *sceneData)
|
||||
: _sceneData(sceneData) {}
|
||||
|
||||
void beginRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
const auto &sceneData = get(SceneTag{}, vertID, *rg.renderGraph);
|
||||
if (sceneData.camera && sceneData.camera->getGeometryRenderer()) {
|
||||
sceneData.camera->getGeometryRenderer()->render(rg.currentRenderPass, rg.primaryCommandBuffer, _sceneData);
|
||||
}
|
||||
}
|
||||
|
||||
void endRenderCommand(const CustomRenderGraphContext &rg, RenderGraph::vertex_descriptor vertID) override {
|
||||
std::ignore = vertID;
|
||||
std::ignore = rg;
|
||||
}
|
||||
|
||||
private:
|
||||
pipeline::PipelineSceneData *_sceneData{nullptr};
|
||||
};
|
||||
#endif
|
||||
|
||||
NativePipeline::NativePipeline(const allocator_type &alloc) noexcept
|
||||
: device(gfx::Device::getInstance()),
|
||||
globalDSManager(std::make_unique<pipeline::GlobalDSManager>()),
|
||||
@@ -1385,6 +1437,10 @@ bool NativePipeline::activate(gfx::Swapchain *swapchainIn) {
|
||||
pipelineSceneData->activate(device);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
DebugRenderer::getInstance()->activate(device);
|
||||
addCustomRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND, std::make_shared<DebugRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
addCustomRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND, std::make_shared<GeometryRendererRenderCommand>(getPipelineSceneData()));
|
||||
#endif
|
||||
// generate macros here rather than construct func because _clusterEnabled
|
||||
// switch may be changed in root.ts setRenderPipeline() function which is after
|
||||
|
||||
@@ -913,6 +913,13 @@ SceneBuilder *NativeRenderQueueBuilder::addScene(
|
||||
data);
|
||||
}
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (any(sceneFlags & SceneFlags::GEOMETRY)) {
|
||||
auto &data = get(RenderGraph::DataTag{}, *renderGraph, sceneID);
|
||||
data.custom = cc::pipeline::GEOMETRY_RENDERER_COMMAND;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (any(sceneFlags & SceneFlags::UI)) {
|
||||
CC_EXPECTS(camera);
|
||||
const auto passOrSubpassId = parent(nodeID, *renderGraph);
|
||||
@@ -1086,6 +1093,31 @@ void NativeRenderQueueBuilder::addProfiler(const scene::Camera *camera) {
|
||||
*renderGraph,
|
||||
passOrSubpassId);
|
||||
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
const auto debugId = addVertex2(
|
||||
BlitTag{},
|
||||
std::forward_as_tuple("DebugRenderer"),
|
||||
std::forward_as_tuple(),
|
||||
std::forward_as_tuple(),
|
||||
std::forward_as_tuple(),
|
||||
std::forward_as_tuple(
|
||||
IntrusivePtr<Material>{},
|
||||
RenderGraph::null_vertex(),
|
||||
SceneFlags::NONE,
|
||||
nullptr,
|
||||
BlitType::FULLSCREEN_QUAD),
|
||||
*renderGraph,
|
||||
queueId);
|
||||
auto &debugData = get(RenderGraph::DataTag{}, *renderGraph, debugId);
|
||||
debugData.custom = cc::pipeline::DEBUG_RENDERER_COMMAND;
|
||||
setCameraUBOValues(
|
||||
*camera,
|
||||
*layoutGraph,
|
||||
*pipelineRuntime->getPipelineSceneData(),
|
||||
camera->getScene() ? camera->getScene()->getMainLight() : nullptr,
|
||||
debugData);
|
||||
#endif
|
||||
|
||||
const auto sceneId = addVertex2(
|
||||
BlitTag{},
|
||||
std::forward_as_tuple("Profiler"),
|
||||
|
||||
@@ -647,8 +647,8 @@ void LightingStage::fgTransparent(scene::Camera *camera) {
|
||||
|
||||
_planarShadowQueue->recordCommandBuffer(_device, table.getRenderPass(), cmdBuff);
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (camera->getGeometryRenderer()) {
|
||||
camera->getGeometryRenderer()->render(table.getRenderPass(), cmdBuff, pipeline->getPipelineSceneData());
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({table.getRenderPass(), cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -228,7 +228,9 @@ void PostProcessStage::render(scene::Camera *camera) {
|
||||
_uiPhase->render(camera, renderPass);
|
||||
renderProfiler(renderPass, cmdBuff, pipeline->getProfiler(), camera);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
renderDebugRenderer(renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera);
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -23,9 +23,6 @@
|
||||
****************************************************************************/
|
||||
|
||||
#include "ForwardStage.h"
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
#include "../GeometryRenderer.h"
|
||||
#endif
|
||||
#include "../InstancedBuffer.h"
|
||||
#include "../PipelineSceneData.h"
|
||||
#include "../PipelineUBO.h"
|
||||
@@ -262,15 +259,17 @@ void ForwardStage::render(scene::Camera *camera) {
|
||||
}
|
||||
|
||||
#if CC_USE_GEOMETRY_RENDERER
|
||||
if (camera->getGeometryRenderer()) {
|
||||
camera->getGeometryRenderer()->render(renderPass, cmdBuff, pipeline->getPipelineSceneData());
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::GEOMETRY_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
|
||||
_uiPhase->render(camera, renderPass);
|
||||
renderProfiler(renderPass, cmdBuff, _pipeline->getProfiler(), camera);
|
||||
#if CC_USE_DEBUG_RENDERER
|
||||
renderDebugRenderer(renderPass, cmdBuff, _pipeline->getPipelineSceneData(), camera);
|
||||
if (auto *command = pipeline->getRenderCommand(cc::pipeline::DEBUG_RENDERER_COMMAND)) {
|
||||
command->beginRenderCommand({renderPass, cmdBuff, pipeline->getPipelineSceneData(), camera});
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ float LODGroup::getScreenUsagePercentage(const Camera *camera) const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto distance = 0;
|
||||
float distance = 0.0F;
|
||||
if (camera->getProjectionType() == CameraProjection::PERSPECTIVE) {
|
||||
Vec3 tmp{_localBoundaryCenter};
|
||||
tmp.transformMat4(_node->getWorldMatrix());
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
"type": "github",
|
||||
"owner": "cocos",
|
||||
"name": "cocos-engine-external",
|
||||
"checkout": "v4.0.0-9"
|
||||
"checkout": "v4.0.0-10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#include <unordered_map>
|
||||
#include "gtest/gtest.h"
|
||||
#include "platform/interfaces/modules/canvas/CanvasFont.h"
|
||||
|
||||
namespace {
|
||||
|
||||
std::string expectedFamily(const std::string &family) {
|
||||
#if CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
return "sans-serif";
|
||||
#else
|
||||
return family;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
using cc::detail::parseCanvasFont;
|
||||
|
||||
TEST(CanvasFontCompatibilityTest, ExplicitSerializationKeepsCollidingAliasesDistinct) {
|
||||
// Quotes in a registered key are data; quotes in the descriptor are CSS syntax.
|
||||
const std::unordered_map<std::string, std::string> registry = {
|
||||
{"Example_LABEL", "plain.ttf"},
|
||||
{R"("Example_LABEL")", "literal-quotes.ttf"},
|
||||
{"sans-serif", "system"},
|
||||
};
|
||||
const char *plain = R"(40px "Example_LABEL")";
|
||||
const char *literalQuotes = R"(40px "\"Example_LABEL\"")";
|
||||
const auto plainFont = parseCanvasFont(plain);
|
||||
const auto quotedFont = parseCanvasFont(literalQuotes);
|
||||
EXPECT_EQ(plainFont.family, expectedFamily("Example_LABEL"));
|
||||
EXPECT_EQ(quotedFont.family, expectedFamily(R"("Example_LABEL")"));
|
||||
#if CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
EXPECT_EQ(registry.at(plainFont.family), "system");
|
||||
EXPECT_EQ(registry.at(quotedFont.family), "system");
|
||||
#else
|
||||
EXPECT_EQ(registry.at(plainFont.family), "plain.ttf");
|
||||
EXPECT_EQ(registry.at(quotedFont.family), "literal-quotes.ttf");
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(CanvasFontCompatibilityTest, MigratedAliasesKeepLegacySizeAndStyles) {
|
||||
const char *description = R"(italic bold 12.5px "\"My Font_LABEL\"")";
|
||||
const auto font = parseCanvasFont(description);
|
||||
EXPECT_EQ(font.family, expectedFamily(R"("My Font_LABEL")"));
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
EXPECT_FLOAT_EQ(font.size, 12.5F);
|
||||
#else
|
||||
EXPECT_FLOAT_EQ(font.size, 12.F);
|
||||
#endif
|
||||
EXPECT_TRUE(font.bold);
|
||||
EXPECT_TRUE(font.italic);
|
||||
}
|
||||
|
||||
TEST(CanvasFontCompatibilityTest, DoesNotDecodeLiteralQuotesTwice) {
|
||||
const char *escaped = R"(40px "\"Example_LABEL\"")";
|
||||
const char *hexEscaped = R"(40px "\22 Example_LABEL\22 ")";
|
||||
const auto expected = expectedFamily(R"("Example_LABEL")");
|
||||
EXPECT_EQ(parseCanvasFont(escaped).family, expected);
|
||||
EXPECT_EQ(parseCanvasFont(hexEscaped).family, expected);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "platform/interfaces/modules/canvas/CanvasFont.h"
|
||||
|
||||
using cc::detail::parseCanvasFont;
|
||||
|
||||
namespace {
|
||||
const char *fallbackFamily() {
|
||||
#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY || CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
return "sans-serif";
|
||||
#else
|
||||
return "Arial";
|
||||
#endif
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(CanvasFontSizeTest, KeepsTheRequestedSizeWhenAQuotedNameIsRejected) {
|
||||
for (const char *input : {u8R"(48px "中文体")", R"(48px "Family3.0")", R"(48px "A, B")", R"(48px "A\a B")"}) {
|
||||
SCOPED_TRACE(input);
|
||||
const auto font = parseCanvasFont(input);
|
||||
EXPECT_EQ(font.family, fallbackFamily());
|
||||
EXPECT_FLOAT_EQ(font.size, 48.F);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CanvasFontSizeTest, KeepsPlatformSizeConversionAndFallbackStyles) {
|
||||
const auto font = parseCanvasFont(u8R"(italic bold 48.5px "中文体")");
|
||||
EXPECT_EQ(font.family, fallbackFamily());
|
||||
EXPECT_TRUE(font.bold);
|
||||
EXPECT_TRUE(font.italic);
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
EXPECT_FLOAT_EQ(font.size, 48.5F);
|
||||
#else
|
||||
EXPECT_FLOAT_EQ(font.size, 48.F);
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(CanvasFontSizeTest, DoesNotRelaxMalformedDescriptions) {
|
||||
for (const char *input : {u8R"(bad 48px "中文体")", "48px \"unterminated", u8R"(48px "中文体", Arial)"}) {
|
||||
SCOPED_TRACE(input);
|
||||
const auto font = parseCanvasFont(input);
|
||||
EXPECT_EQ(font.family, fallbackFamily());
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
EXPECT_FLOAT_EQ(font.size, 30.F);
|
||||
#else
|
||||
EXPECT_FLOAT_EQ(font.size, 48.F);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CanvasFontSizeTest, RejectsUnsafeSizesOnTheRecoveredFallbackPath) {
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
for (const auto &number : {std::string("-1"), std::string(".5"), std::string("2147483648"), std::string(400, '9')}) {
|
||||
SCOPED_TRACE(number);
|
||||
const auto font = parseCanvasFont(number + u8R"(px "中文体")");
|
||||
EXPECT_EQ(font.family, fallbackFamily());
|
||||
EXPECT_FLOAT_EQ(font.size, 30.F);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "platform/interfaces/modules/canvas/CanvasFont.h"
|
||||
|
||||
using cc::detail::parseCanvasFont;
|
||||
|
||||
namespace {
|
||||
const char *fallbackFamily() {
|
||||
#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY || CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
return "sans-serif";
|
||||
#else
|
||||
return "Arial";
|
||||
#endif
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(CanvasFontTest, RestoresPreviouslyRecognizedAssetAliases) {
|
||||
const struct {
|
||||
const char *description;
|
||||
const char *alias;
|
||||
} cases[] = {
|
||||
{R"(40px "Example_LABEL")", "Example_LABEL"},
|
||||
{R"(40px "AlibabaPuHuiTi-3-105-Heavy_LABEL")", "AlibabaPuHuiTi-3-105-Heavy_LABEL"},
|
||||
{R"(40px "\"My Font_LABEL\"")", R"("My Font_LABEL")"},
|
||||
{R"(40px "Demo12px")", "Demo12px"},
|
||||
{R"(40px 'Example_LABEL')", "Example_LABEL"},
|
||||
};
|
||||
for (const auto &item : cases) {
|
||||
SCOPED_TRACE(item.description);
|
||||
const auto font = parseCanvasFont(item.description);
|
||||
#if CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
EXPECT_EQ(font.family, "sans-serif");
|
||||
#else
|
||||
EXPECT_EQ(font.family, item.alias);
|
||||
#endif
|
||||
EXPECT_FLOAT_EQ(font.size, 40.F);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CanvasFontTest, DoesNotExpandNativeFontNameSupport) {
|
||||
for (const char *input : {u8R"(48px "中文体")", R"(48px "Family3.0")", R"(48px "A, B")",
|
||||
R"(48px "A\"B")", R"(48px "\\61")", R"(48px "\0 \d800 \110000 ")",
|
||||
R"(48px "\"Family 3.0_LABEL\"")", R"(48px "A\a B")"}) {
|
||||
SCOPED_TRACE(input);
|
||||
EXPECT_EQ(parseCanvasFont(input).family, fallbackFamily());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CanvasFontTest, ChecksDecodedNamesUsingTheExistingPolicy) {
|
||||
for (const char *input : {R"(40px "\52 egular")", R"(40px "\000052egular")", "40px \"Reg\\\r\nular\""}) {
|
||||
SCOPED_TRACE(input);
|
||||
#if CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
EXPECT_EQ(parseCanvasFont(input).family, "sans-serif");
|
||||
#else
|
||||
EXPECT_EQ(parseCanvasFont(input).family, "Regular");
|
||||
#endif
|
||||
}
|
||||
EXPECT_EQ(parseCanvasFont(R"(40px "\4e2d \6587 ")").family, fallbackFamily());
|
||||
}
|
||||
|
||||
TEST(CanvasFontTest, PreservesLegacyStyleAndFractionalSizeRules) {
|
||||
const auto font = parseCanvasFont(R"(12.5px "BoldItalicOblique-small-caps_LABEL")");
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
EXPECT_FLOAT_EQ(font.size, 12.5F);
|
||||
#else
|
||||
EXPECT_FLOAT_EQ(font.size, 12.F);
|
||||
#endif
|
||||
EXPECT_TRUE(font.bold);
|
||||
EXPECT_TRUE(font.italic);
|
||||
#if CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS || CC_PLATFORM == CC_PLATFORM_OPENHARMONY
|
||||
EXPECT_TRUE(font.oblique);
|
||||
EXPECT_TRUE(font.smallCaps);
|
||||
#else
|
||||
EXPECT_FALSE(font.oblique);
|
||||
EXPECT_FALSE(font.smallCaps);
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(CanvasFontTest, KeepsListsAndMalformedQuotesOnTheLegacyPath) {
|
||||
for (const char *input : {R"(48px "A, B", Arial)", R"(48px "A" extra)", "48px \"unterminated"}) {
|
||||
SCOPED_TRACE(input);
|
||||
const auto font = parseCanvasFont(input);
|
||||
EXPECT_EQ(font.family, fallbackFamily());
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
EXPECT_FLOAT_EQ(font.size, 30.F);
|
||||
#else
|
||||
EXPECT_FLOAT_EQ(font.size, 48.F);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CanvasFontTest, LeavesUnquotedNamesAndExistingDefaultsUnchanged) {
|
||||
const auto invalid = parseCanvasFont("bad description");
|
||||
EXPECT_EQ(invalid.family, fallbackFamily());
|
||||
EXPECT_FLOAT_EQ(invalid.size, 30.F);
|
||||
const auto unquoted = parseCanvasFont("40px Times New Roman");
|
||||
#if CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
EXPECT_EQ(unquoted.family, "Times");
|
||||
#elif CC_PLATFORM == CC_PLATFORM_LINUX
|
||||
EXPECT_EQ(unquoted.family, "sans-serif");
|
||||
#else
|
||||
EXPECT_EQ(unquoted.family, "Times New Roman");
|
||||
#endif
|
||||
}
|
||||
@@ -105,6 +105,12 @@ using namespace cc;
|
||||
%ignore cc::pipeline::GeometryRenderer::activate;
|
||||
%ignore cc::pipeline::GeometryRenderer::render;
|
||||
%ignore cc::pipeline::GeometryRenderer::destroy;
|
||||
%ignore cc::pipeline::RenderCommand;
|
||||
%ignore cc::pipeline::RenderCommandContext;
|
||||
%ignore cc::pipeline::DebugRendererRenderCommand;
|
||||
%ignore cc::pipeline::GeometryRendererRenderCommand;
|
||||
%ignore cc::pipeline::RenderPipeline::addRenderCommand;
|
||||
%ignore cc::pipeline::RenderPipeline::getRenderCommand;
|
||||
|
||||
// ----- Rename Section ------
|
||||
// Brief: Classes, methods or attributes needs to be renamed
|
||||
|
||||
+18
-9
@@ -185,8 +185,9 @@ void GoogleBillingHelper::onBillingServiceDisconnected(JNIEnv* env, jclass clazz
|
||||
if (billingClient) {
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
cc::callJSfunc(it->second.get(), "onBillingServiceDisconnected");
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onBillingServiceDisconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,8 +204,9 @@ void GoogleBillingHelper::onProductDetailsResponse(JNIEnv* env, jclass clazz,
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
std::vector<cc::ProductDetails*> productDetailsList = cc::JniBilling::toProductDetailList(env, productDetailsListObj, tag, startID);
|
||||
cc::callJSfunc(it->second.get(), "onProductDetailsResponse", billingResult, productDetailsList);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onProductDetailsResponse", billingResult, productDetailsList);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,8 +241,9 @@ void GoogleBillingHelper::onConsumeResponse(JNIEnv* env, jclass clazz, jint tag,
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
cc::callJSfunc(it->second.get(), "onConsumeResponse", billingResult, cc::StringUtils::getStringUTFCharsJNI(env, static_cast<jstring>(purchaseToken)));
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onConsumeResponse", billingResult, cc::StringUtils::getStringUTFCharsJNI(env, static_cast<jstring>(purchaseToken)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -256,8 +259,9 @@ void GoogleBillingHelper::onQueryPurchasesResponse(JNIEnv* env, jclass clazz, ji
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
std::vector<cc::Purchase*> purchasesList = cc::JniBilling::toPurchaseList(env, purchasesListObj, tag, startID);
|
||||
cc::callJSfunc(it->second.get(), "onQueryPurchasesResponse", billingResult, purchasesList);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onQueryPurchasesResponse", billingResult, purchasesList);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,8 +276,9 @@ void GoogleBillingHelper::onBillingConfigResponse(JNIEnv* env, jclass clazz, jin
|
||||
if (billingConfigObj) {
|
||||
billingConfig = cc::JniBilling::toBillingConfig(env, billingConfigObj);
|
||||
}
|
||||
cc::callJSfunc(it->second.get(), "onBillingConfigResponse", billingResult, billingConfig);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onBillingConfigResponse", billingResult, billingConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -288,8 +293,9 @@ void GoogleBillingHelper::onAlternativeBillingOnlyTokenResponse(JNIEnv* env, jcl
|
||||
if (alternativeBillingOnlyReportingDetailsObj) {
|
||||
toAlternativeBillingOnlyReporting = cc::JniBilling::toAlternativeBillingOnlyReportingDetails(env, alternativeBillingOnlyReportingDetailsObj);
|
||||
}
|
||||
cc::callJSfunc(it->second.get(), "onAlternativeBillingOnlyTokenResponse", billingResult, toAlternativeBillingOnlyReporting);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onAlternativeBillingOnlyTokenResponse", billingResult, toAlternativeBillingOnlyReporting);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -304,8 +310,9 @@ void GoogleBillingHelper::onExternalOfferReportingDetailsResponse(JNIEnv* env, j
|
||||
if (externalOfferReportingDetailsObj) {
|
||||
externalOfferReportingDetails = cc::JniBilling::toExternalOfferReportingDetails(env, externalOfferReportingDetailsObj);
|
||||
}
|
||||
cc::callJSfunc(it->second.get(), "onExternalOfferReportingDetailsResponse", billingResult, externalOfferReportingDetails);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onExternalOfferReportingDetailsResponse", billingResult, externalOfferReportingDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -332,8 +339,9 @@ void GoogleBillingHelper::onInAppMessageResponse(JNIEnv* env, jclass clazz, jint
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* inAppMessageResult = cc::JniBilling::toInAppMessageResult(env, inAppMessageResultObj);
|
||||
cc::callJSfunc(it->second.get(), "onInAppMessageResponse", inAppMessageResult);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), "onInAppMessageResponse", inAppMessageResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,8 +352,9 @@ void GoogleBillingHelper::responseOnlyWithBillingResult(const std::string& funct
|
||||
auto it = billingClient->_listeners.find(callbackId);
|
||||
if (it != billingClient->_listeners.end()) {
|
||||
auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj);
|
||||
cc::callJSfunc(it->second.get(), functionName.c_str(), billingResult);
|
||||
scopedListener listener(it->second.get());
|
||||
billingClient->_listeners.erase(it);
|
||||
cc::callJSfunc(listener.get(), functionName.c_str(), billingResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -178,7 +178,7 @@ void PlayTask::onTaskSuccess(int listerId, void* obj) {
|
||||
// Therefore, it should be removed first.
|
||||
scopedListener listener(it->second.get());
|
||||
_listeners.erase(it);
|
||||
callJSfuncWithJObject(it->second.get(), "onSuccess", obj);
|
||||
callJSfuncWithJObject(listener.get(), "onSuccess", obj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Generated
+7
-6
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.33",
|
||||
"version": "4.0.0-beta.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.33",
|
||||
"version": "4.0.0-beta.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -15,7 +15,7 @@
|
||||
"@cocos/cannon": "1.2.8",
|
||||
"@cocos/ccbuild": "^2.3.21",
|
||||
"@cocos/dragonbones-js": "^1.0.1",
|
||||
"@cocos/engine-pal": "^1.0.4",
|
||||
"@cocos/engine-pal": "^1.0.6",
|
||||
"@cocos/engine-platforms": "^1.0.6",
|
||||
"@types/jest": "^24.9.1"
|
||||
},
|
||||
@@ -2568,9 +2568,10 @@
|
||||
"integrity": "sha512-1bWAW8td2WTGicyCqxtpIjc1YuK5EzMWfMEWaJlskPAQwLS0JfxEGka71sZ1BzudiWiKS7hPMg+FvXr5NRnVwQ=="
|
||||
},
|
||||
"node_modules/@cocos/engine-pal": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmmirror.com/@cocos/engine-pal/-/engine-pal-1.0.4.tgz",
|
||||
"integrity": "sha512-VtvO0xE2ZviVtwqWn4P6cysn2BX7QABm9sNc1rfy4gy+FHtiwSMkLLL3l3Faw+yZiTE6EwxjPvnc96Igb7mNuQ=="
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@cocos/engine-pal/-/engine-pal-1.0.6.tgz",
|
||||
"integrity": "sha512-CurR0yDbdRUSyOu8R939Y0jq1UDd+ZTFyPKDN9J9SlsLRAjImtIwGcfQ+yohdgr3UxV4oFuLEjIAdcHJTvMafg==",
|
||||
"license": "UNLICENSED"
|
||||
},
|
||||
"node_modules/@cocos/engine-platforms": {
|
||||
"version": "1.0.6",
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cocos-creator",
|
||||
"version": "4.0.0-alpha.33",
|
||||
"version": "4.0.0-beta.2",
|
||||
"description": "Cocos Creator is a cross-platform 2D & 3D game engine written in C++ and TypeScript, licensed under MIT.",
|
||||
"homepage": "http://www.cocos.com",
|
||||
"license": "MIT",
|
||||
@@ -25,7 +25,8 @@
|
||||
"build:cli-min": "npm run build:debug-infos && node ./scripts/build-cli-minified",
|
||||
"clear": "node ./scripts/clear-cache.js",
|
||||
"clear:platform": "node ./native/utils/clear-platform.js && node ./scripts/clear-file.js",
|
||||
"test": "tsc --noEmit && jest",
|
||||
"test": "npm run test:pal && tsc --noEmit && jest",
|
||||
"test:pal": "node --test tests/scripts/spread-pal.test.cjs tests/scripts/pal-worker-types.test.cjs",
|
||||
"test:dts": "npx tsc ./scripts/test-declarations/test.d.ts",
|
||||
"update:engine-version": "node ./scripts/checkout-engine-version.js",
|
||||
"update:native-external": "node ./native/utils/update-external.js",
|
||||
@@ -83,7 +84,7 @@
|
||||
"@cocos/cannon": "1.2.8",
|
||||
"@cocos/ccbuild": "^2.3.21",
|
||||
"@cocos/dragonbones-js": "^1.0.1",
|
||||
"@cocos/engine-pal": "^1.0.4",
|
||||
"@cocos/engine-pal": "^1.0.6",
|
||||
"@cocos/engine-platforms": "^1.0.6",
|
||||
"@types/jest": "^24.9.1"
|
||||
},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user