diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 94586be833d..1edfb8f1042 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -655,7 +655,15 @@ should set resolutionPolicy ### 2300 -The touches is more than MAX_TOUCHES, nUnusedIndex = %s +The touches is more than MAX_TOUCHES. + +### 2301 + +Cannot create the same touch object. + +### 2302 + +The touches is more than MAX_TOUCHES, release touch id %s. ### 2400 @@ -3837,6 +3845,10 @@ ProgressBar non-FILLED mode only works when barSprite's Type is non-FILLED! CopyTextureToBuffers: not supported texture target. +### 16400 + +Limit values to be greater than 0 + ### 16401 beginRenderPass: Only primary command buffer is supported. @@ -3856,3 +3868,7 @@ Block '%s' does not bound ### 16405 This device does not support WebGL2 + +### 16406 + +Can't find the spriteFrame of tilesets %s \ No newline at end of file diff --git a/cc.config.json b/cc.config.json index 04ab920b1cb..32568ae0a57 100644 --- a/cc.config.json +++ b/cc.config.json @@ -608,7 +608,6 @@ "dynamic": true }, - "DEBUG": { "comment": "Running debug mode.", "type": "boolean", @@ -616,6 +615,7 @@ "ccGlobal": true, "internal": false }, + "SERVER_MODE": { "comment": "Running in the server mode.", "type": "boolean", @@ -713,5 +713,12 @@ "readOnly", "displayName", "tooltip", "group", "range", "rangeMin", "rangeMax", "rangeStep", "slide", "displayOrder", "unit", "radian", "multiline", "disallowAnimation" ] + }, + + "treeShake": { + "noSideEffectFiles": [ + "cocos/serialization/instantiate-jit.ts", + "cocos/game/splash-screen.ts" + ] } } diff --git a/cc.config.schema.json b/cc.config.schema.json index dff5c7da513..22fb1a4a3ec 100644 --- a/cc.config.schema.json +++ b/cc.config.schema.json @@ -56,6 +56,10 @@ "optimizeDecorators": { "$ref": "#/definitions/IOptimizeDecorators", "description": "The decorators to be optimize when build engine." + }, + "treeShake": { + "$ref": "#/definitions/ITreeShakeConfig", + "description": "The TreeShake config" } }, "required": [ @@ -193,6 +197,21 @@ ], "type": "object" }, + "ITreeShakeConfig": { + "additionalProperties": false, + "properties": { + "noSideEffectFiles": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "noSideEffectFiles" + ], + "type": "object" + }, "IndexConfig": { "additionalProperties": false, "properties": { diff --git a/cocos/2d/assembler/label/font-utils.ts b/cocos/2d/assembler/label/font-utils.ts index 4926e545665..1afe602c179 100644 --- a/cocos/2d/assembler/label/font-utils.ts +++ b/cocos/2d/assembler/label/font-utils.ts @@ -28,7 +28,7 @@ import { ImageAsset, Texture2D } from '../../../asset/assets'; import { PixelFormat } from '../../../asset/assets/asset-enum'; import { BufferTextureCopy } from '../../../gfx'; import { safeMeasureText, BASELINE_RATIO, MIDDLE_RATIO, getBaselineOffset, getSymbolCodeAt } from '../../utils/text-utils'; -import { director, Director } from '../../../game/director'; +import { director, DirectorEvent } from '../../../game/director'; import { ccwindow } from '../../../core/global-exports'; export interface ISharedLabelData { @@ -278,7 +278,7 @@ export class LetterAtlas { this._halfBleed = bleed / 2; this._width = width; this._height = height; - director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); + director.on(DirectorEvent.BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); } public insertLetterTexture (letterTexture: LetterTexture): FontLetterDefinition | null { diff --git a/cocos/2d/assembler/label/index.ts b/cocos/2d/assembler/label/index.ts index 1c36681072a..64d90c481ff 100644 --- a/cocos/2d/assembler/label/index.ts +++ b/cocos/2d/assembler/label/index.ts @@ -23,7 +23,7 @@ */ import { BitmapFont } from '../../assets'; -import { Label } from '../../components'; +import { CacheMode, Label } from '../../components'; import { IAssemblerManager } from '../../renderer/base'; import { bmfont } from './bmfont'; import { letter } from './letter'; @@ -36,7 +36,7 @@ const labelAssembler: IAssemblerManager = { if (comp.font instanceof BitmapFont) { assembler = bmfont; - } else if (comp.cacheMode === Label.CacheMode.CHAR) { + } else if (comp.cacheMode === CacheMode.CHAR) { assembler = letter; } diff --git a/cocos/2d/assembler/label/ttfUtils.ts b/cocos/2d/assembler/label/ttfUtils.ts index c4ff09c4aa0..be89965aae2 100644 --- a/cocos/2d/assembler/label/ttfUtils.ts +++ b/cocos/2d/assembler/label/ttfUtils.ts @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { Label } from '../../components'; +import { CacheMode, Label } from '../../components'; import { ISharedLabelData } from './font-utils'; import { UITransform } from '../../framework/ui-transform'; import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager'; @@ -207,14 +207,14 @@ export const ttfUtils = { }, _calDynamicAtlas (comp: Label, outputLayoutData: TextOutputLayoutData): void { - if (comp.cacheMode !== Label.CacheMode.BITMAP || outputLayoutData.canvasSize.width <= 0 || outputLayoutData.canvasSize.height <= 0) return; + if (comp.cacheMode !== CacheMode.BITMAP || outputLayoutData.canvasSize.width <= 0 || outputLayoutData.canvasSize.height <= 0) return; const frame = comp.ttfSpriteFrame!; dynamicAtlasManager.packToDynamicAtlas(comp, frame); // TODO update material and uv }, _resetDynamicAtlas (comp: Label): void { - if (comp.cacheMode !== Label.CacheMode.BITMAP) return; + if (comp.cacheMode !== CacheMode.BITMAP) return; const frame = comp.ttfSpriteFrame!; dynamicAtlasManager.deleteAtlasSpriteFrame(frame); frame._resetDynamicAtlasFrame(); diff --git a/cocos/2d/assets/sprite-frame.ts b/cocos/2d/assets/sprite-frame.ts index a0159c6729b..6588db3dbcf 100644 --- a/cocos/2d/assets/sprite-frame.ts +++ b/cocos/2d/assets/sprite-frame.ts @@ -167,6 +167,10 @@ export interface ISpriteFrameInitInfo { const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }]; +export enum SpriteFrameEvent { + UV_UPDATED = 'uv_updated', +} + /** * @en * A `SpriteFrame` support several types. @@ -262,7 +266,7 @@ export class SpriteFrame extends Asset { * @en uv update event. * @zh uv 更新事件。 */ - public static EVENT_UV_UPDATED = 'uv_updated'; + public static EVENT_UV_UPDATED = SpriteFrameEvent.UV_UPDATED; public static MeshType = MeshType; /** @@ -999,7 +1003,7 @@ export class SpriteFrame extends Asset { // UV update event for components to update uv buffer // CalculateUV will trigger _calculateSlicedUV so it's enough to emit here - this.emit(SpriteFrame.EVENT_UV_UPDATED, this); + this.emit(SpriteFrameEvent.UV_UPDATED, this); } /** diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 1d062d2dc3c..eb1b2621d67 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -26,7 +26,7 @@ import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, range, editable, serializable, visible } from 'cc.decorator'; import { BUILD, EDITOR } from 'internal:constants'; import { SpriteAtlas } from '../assets/sprite-atlas'; -import { SpriteFrame } from '../assets/sprite-frame'; +import { SpriteFrame, SpriteFrameEvent } from '../assets/sprite-frame'; import { Vec2, cclegacy, ccenum, clamp, warnID } from '../../core'; import { IBatcher } from '../renderer/i-batcher'; import { UIRenderer, InstanceMaterialType } from '../framework/ui-renderer'; @@ -151,7 +151,7 @@ enum SizeMode { } ccenum(SizeMode); -enum EventType { +export enum SpriteEventType { SPRITE_FRAME_CHANGED = 'spriteframe-changed', } @@ -214,7 +214,7 @@ export class Sprite extends UIRenderer { this.markForUpdateRenderData(); this._applySpriteFrame(lastSprite); if (EDITOR) { - this.node.emit(EventType.SPRITE_FRAME_CHANGED, this); + this.node.emit(SpriteEventType.SPRITE_FRAME_CHANGED, this); } } @@ -458,7 +458,7 @@ export class Sprite extends UIRenderer { * @en Event types for sprite. * @zh sprite 的事件类型。 */ - public static EventType = EventType; + public static EventType = SpriteEventType; @serializable protected _spriteFrame: SpriteFrame | null = null; @@ -500,7 +500,7 @@ export class Sprite extends UIRenderer { if (spriteFrame) { this._updateUVs(); if (this._type === SpriteType.SLICED) { - spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); + spriteFrame.on(SpriteFrameEvent.UV_UPDATED, this._updateUVs, this); } } } @@ -508,7 +508,7 @@ export class Sprite extends UIRenderer { public onDisable (): void { super.onDisable(); if (this._spriteFrame && this._type === SpriteType.SLICED) { - this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); + this._spriteFrame.off(SpriteFrameEvent.UV_UPDATED, this._updateUVs, this); } } @@ -616,9 +616,9 @@ export class Sprite extends UIRenderer { // Only Sliced type need update uv when sprite frame insets changed if (this._spriteFrame) { if (this._type === SpriteType.SLICED) { - this._spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); + this._spriteFrame.on(SpriteFrameEvent.UV_UPDATED, this._updateUVs, this); } else { - this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); + this._spriteFrame.off(SpriteFrameEvent.UV_UPDATED, this._updateUVs, this); } } } @@ -686,7 +686,7 @@ export class Sprite extends UIRenderer { const spriteFrame = this._spriteFrame; if (oldFrame && this._type === SpriteType.SLICED) { - oldFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); + oldFrame.off(SpriteFrameEvent.UV_UPDATED, this._updateUVs, this); } let textureChanged = false; @@ -706,7 +706,7 @@ export class Sprite extends UIRenderer { } this._applySpriteSize(); if (this._type === SpriteType.SLICED) { - spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); + spriteFrame.on(SpriteFrameEvent.UV_UPDATED, this._updateUVs, this); } } } diff --git a/cocos/2d/event/pointer-event-dispatcher.ts b/cocos/2d/event/pointer-event-dispatcher.ts index 819d834d9f8..ec4e08f3354 100644 --- a/cocos/2d/event/pointer-event-dispatcher.ts +++ b/cocos/2d/event/pointer-event-dispatcher.ts @@ -31,18 +31,18 @@ import { InputEventType } from '../../input/types/event-enum'; import { EventDispatcherPriority, IEventDispatcher } from '../../input/input'; const mouseEvents = [ - Input.EventType.MOUSE_DOWN, - Input.EventType.MOUSE_MOVE, - Input.EventType.MOUSE_UP, - Input.EventType.MOUSE_WHEEL, - Input.EventType.MOUSE_LEAVE, - Input.EventType.MOUSE_ENTER, + InputEventType.MOUSE_DOWN, + InputEventType.MOUSE_MOVE, + InputEventType.MOUSE_UP, + InputEventType.MOUSE_WHEEL, + InputEventType.MOUSE_LEAVE, + InputEventType.MOUSE_ENTER, ]; const touchEvents = [ - Input.EventType.TOUCH_START, - Input.EventType.TOUCH_MOVE, - Input.EventType.TOUCH_END, - Input.EventType.TOUCH_CANCEL, + InputEventType.TOUCH_START, + InputEventType.TOUCH_MOVE, + InputEventType.TOUCH_END, + InputEventType.TOUCH_CANCEL, ]; class PointerEventDispatcher implements IEventDispatcher { diff --git a/cocos/2d/framework/canvas.ts b/cocos/2d/framework/canvas.ts index 70366f4d095..eb2f1fa18ca 100644 --- a/cocos/2d/framework/canvas.ts +++ b/cocos/2d/framework/canvas.ts @@ -26,7 +26,7 @@ import { ccclass, help, disallowMultiple, executeInEditMode, executionOrder, menu, tooltip, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { Camera } from '../../misc/camera-component'; +import { Camera, CameraEvent } from '../../misc/camera-component'; import { Widget } from '../../ui/widget'; import { Vec3, screen, Enum, cclegacy, visibleRect } from '../../core'; import { view } from '../../ui/view'; @@ -182,7 +182,7 @@ export class Canvas extends RenderRoot2D { if (!EDITOR) { if (this._cameraComponent) { this._cameraComponent._createCamera(); - this._cameraComponent.node.on(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); + this._cameraComponent.node.on(CameraEvent.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); } } @@ -203,14 +203,14 @@ export class Canvas extends RenderRoot2D { public onEnable (): void { super.onEnable(); if (!EDITOR && this._cameraComponent) { - this._cameraComponent.node.on(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); + this._cameraComponent.node.on(CameraEvent.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); } } public onDisable (): void { super.onDisable(); if (this._cameraComponent) { - this._cameraComponent.node.off(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); + this._cameraComponent.node.off(CameraEvent.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized); } } diff --git a/cocos/2d/framework/ui-transform.ts b/cocos/2d/framework/ui-transform.ts index 7cea00b181d..97217c6ba94 100644 --- a/cocos/2d/framework/ui-transform.ts +++ b/cocos/2d/framework/ui-transform.ts @@ -26,7 +26,7 @@ import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, displa import { EDITOR } from 'internal:constants'; import { Component, Node } from '../../scene-graph'; import { Mat4, Rect, Size, Vec2, Vec3, geometry, warnID, visibleRect, approx, EPSILON } from '../../core'; -import { Director, director } from '../../game/director'; +import { director, DirectorEvent } from '../../game/director'; import { NodeEventType } from '../../scene-graph/node-event'; import { IMask } from '../../scene-graph/node-event-processor'; import { Mask } from '../components/mask'; @@ -815,5 +815,5 @@ export class UITransform extends Component { } // HACK -director.on(Director.EVENT_AFTER_UPDATE, UITransform._sortSiblings); -director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, UITransform._cleanChangeMap); +director.on(DirectorEvent.AFTER_UPDATE, UITransform._sortSiblings); +director.on(DirectorEvent.BEFORE_SCENE_LAUNCH, UITransform._cleanChangeMap); diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index 8cf99c73677..3a272c470ce 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -35,7 +35,7 @@ import { Root } from '../../root'; import { Node } from '../../scene-graph'; import { Stage, StencilManager } from './stencil-manager'; import { DrawBatch2D } from './draw-batch'; -import { ModelLocalBindings, UBOLocal } from '../../rendering/define'; +import { ModelLocalBindings, UBOLocal, UBOLocalEnum } from '../../rendering/define'; import { SpriteFrame } from '../assets'; import { TextureBase } from '../../asset/assets/texture-base'; import { IBatcher } from './i-batcher'; @@ -44,7 +44,7 @@ import { getAttributeStride, vfmt, vfmtPosUvColor } from './vertex-format'; import { updateOpacity } from '../assembler/utils'; import { BaseRenderData, MeshRenderData } from './render-data'; import { UIMeshRenderer } from '../components/ui-mesh-renderer'; -import { NativeBatcher2d, NativeUIMeshBuffer } from './native-2d'; +import { NativeBatcher2d } from './native-2d'; import { MeshBuffer } from './mesh-buffer'; import { scene } from '../../render-scene'; import { builtinResMgr } from '../../asset/asset-manager'; @@ -973,12 +973,12 @@ class LocalDescriptorSet { constructor () { const device = deviceManager.gfxDevice; - this._localData = new Float32Array(UBOLocal.COUNT); + this._localData = new Float32Array(UBOLocalEnum.COUNT); this._localBuffer = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOLocal.SIZE, - UBOLocal.SIZE, + UBOLocalEnum.SIZE, + UBOLocalEnum.SIZE, )); } @@ -1040,7 +1040,7 @@ class LocalDescriptorSet { } if (this._transformUpdate) { const worldMatrix = node.worldMatrix; - Mat4.toArray(this._localData!, worldMatrix, UBOLocal.MAT_WORLD_OFFSET); + Mat4.toArray(this._localData!, worldMatrix, UBOLocalEnum.MAT_WORLD_OFFSET); Mat4.invert(m4_1, worldMatrix); Mat4.transpose(m4_1, m4_1); @@ -1052,7 +1052,7 @@ class LocalDescriptorSet { const factor = 1.0 / Math.sqrt(det); Mat4.multiplyScalar(m4_1, m4_1, factor); } - Mat4.toArray(this._localData!, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET); + Mat4.toArray(this._localData!, m4_1, UBOLocalEnum.MAT_WORLD_IT_OFFSET); this._localBuffer!.update(this._localData!); this._transformUpdate = false; } diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index c6cabde2724..40ea755c6e3 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -23,7 +23,7 @@ */ import { Material } from '../../asset/assets'; -import { Attribute, Device, Sampler, Texture } from '../../gfx'; +import { Attribute, Sampler, Texture } from '../../gfx'; import { Node } from '../../scene-graph'; import { Model } from '../../render-scene/scene'; diff --git a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts index 7ce13edeadc..993b3aaa35b 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts @@ -25,7 +25,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { System, macro, cclegacy } from '../../../core'; import { Atlas, DynamicAtlasTexture } from './atlas'; -import { director } from '../../../game'; +import { director, DirectorEvent } from '../../../game'; import { SpriteFrame } from '../../assets'; import { Filter } from '../../../gfx/base/define'; import { TextureBase } from '../../../asset/assets/texture-base'; @@ -74,10 +74,10 @@ export class DynamicAtlasManager extends System { if (value) { this.reset(); - cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); + director.on(DirectorEvent.BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); } else { this.reset(); - cclegacy.director.off(cclegacy.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); + director.off(DirectorEvent.BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); } this._enabled = value; diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 5011a6e09d8..7b63aa9732e 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -787,7 +787,7 @@ export class Mesh extends Asset { const rotate = worldMatrix && new Quat(); const boundingBox = worldMatrix && new geometry.AABB(); if (rotate) { - worldMatrix!.getRotation(rotate); + worldMatrix.getRotation(rotate); } if (!this._initialized) { const struct = JSON.parse(JSON.stringify(mesh._struct)) as Mesh.IStruct; diff --git a/cocos/3d/assets/morph-rendering.ts b/cocos/3d/assets/morph-rendering.ts index 861c3363de7..f03ae03e5a1 100644 --- a/cocos/3d/assets/morph-rendering.ts +++ b/cocos/3d/assets/morph-rendering.ts @@ -28,12 +28,12 @@ import { import { Mesh } from './mesh'; import { Texture2D } from '../../asset/assets/texture-2d'; import { ImageAsset } from '../../asset/assets/image-asset'; -import { UBOMorph, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, +import { UBOMorph, UBOMorphEnum, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, UNIFORM_POSITION_MORPH_TEXTURE_BINDING, UNIFORM_TANGENT_MORPH_TEXTURE_BINDING } from '../../rendering/define'; import { Morph, SubMeshMorph } from './morph'; import { assertIsNonNullable, assertIsTrue, warn, bits, nextPow2, cclegacy, warnID } from '../../core'; import { IMacroPatch } from '../../render-scene'; -import { PixelFormat } from '../../asset/assets/asset-enum'; +import { Filter, PixelFormat, WrapMode } from '../../asset/assets/asset-enum'; /** * True if force to use cpu computing based sub-mesh rendering. @@ -92,11 +92,11 @@ export function createMorphRendering (mesh: Mesh, gfxDevice: Device): MorphRende /** * @en Standard morph rendering class, it supports both GPU and CPU based morph blending. - * If sub mesh morph targets count is less than [[pipeline.UBOMorph.MAX_MORPH_TARGET_COUNT]], then GPU based blending is enabled. + * If sub mesh morph targets count is less than [[pipeline.UBOMorphEnum.MAX_MORPH_TARGET_COUNT]], then GPU based blending is enabled. * Each of the sub-mesh morph has its own [[MorphRenderingInstance]], * its morph target weights, render pipeline state and strategy of morph blending are controlled separately. * @zh 标准形变网格渲染类,它同时支持 CPU 和 GPU 的形变混合计算。 - * 如果子网格形变目标数量少于 [[pipeline.UBOMorph.MAX_MORPH_TARGET_COUNT]],那么就会使用基于 GPU 的形变混合计算。 + * 如果子网格形变目标数量少于 [[pipeline.UBOMorphEnum.MAX_MORPH_TARGET_COUNT]],那么就会使用基于 GPU 的形变混合计算。 * 每个子网格形变都使用自己独立的 [[MorphRenderingInstance]],它的形变目标权重、渲染管线状态和形变混合计算策略都是独立控制的。 */ export class StdMorphRendering implements MorphRendering { @@ -117,7 +117,7 @@ export class StdMorphRendering implements MorphRendering { continue; } - if (preferCpuComputing || subMeshMorph.targets.length > UBOMorph.MAX_MORPH_TARGET_COUNT) { + if (preferCpuComputing || subMeshMorph.targets.length > UBOMorphEnum.MAX_MORPH_TARGET_COUNT) { this._subMeshRenderings[iSubMesh] = new CpuComputing( this._mesh, iSubMesh, @@ -489,12 +489,12 @@ class MorphUniforms { constructor (gfxDevice: Device, targetCount: number) { this._targetCount = targetCount; - this._localBuffer = new DataView(new ArrayBuffer(UBOMorph.SIZE)); + this._localBuffer = new DataView(new ArrayBuffer(UBOMorphEnum.SIZE)); this._remoteBuffer = gfxDevice.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOMorph.SIZE, - UBOMorph.SIZE, + UBOMorphEnum.SIZE, + UBOMorphEnum.SIZE, )); } @@ -510,19 +510,19 @@ class MorphUniforms { assertIsTrue(weights.length === this._targetCount); const isLittleEndian = cclegacy.sys.isLittleEndian as boolean; for (let iWeight = 0; iWeight < weights.length; ++iWeight) { - this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_WEIGHTS + 4 * iWeight, weights[iWeight], isLittleEndian); + this._localBuffer.setFloat32(UBOMorphEnum.OFFSET_OF_WEIGHTS + 4 * iWeight, weights[iWeight], isLittleEndian); } } public setMorphTextureInfo (width: number, height: number): void { const isLittleEndian = cclegacy.sys.isLittleEndian as boolean; - this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH, width, isLittleEndian); - this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT, height, isLittleEndian); + this._localBuffer.setFloat32(UBOMorphEnum.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH, width, isLittleEndian); + this._localBuffer.setFloat32(UBOMorphEnum.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT, height, isLittleEndian); } public setVerticesCount (count: number): void { const isLittleEndian = cclegacy.sys.isLittleEndian as boolean; - this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_VERTICES_COUNT, count, isLittleEndian); + this._localBuffer.setFloat32(UBOMorphEnum.OFFSET_OF_VERTICES_COUNT, count, isLittleEndian); } public commit (): void { @@ -550,12 +550,12 @@ function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number): { if (hasFeatureFloatTexture) { pixelRequired = vec4Capacity; pixelBytes = 16; - pixelFormat = Texture2D.PixelFormat.RGBA32F; + pixelFormat = PixelFormat.RGBA32F; UpdateViewConstructor = Float32Array; } else { pixelRequired = 4 * vec4Capacity; pixelBytes = 4; - pixelFormat = Texture2D.PixelFormat.RGBA8888; + pixelFormat = PixelFormat.RGBA8888; UpdateViewConstructor = Uint8Array; } @@ -583,9 +583,9 @@ function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number): { format: pixelFormat, }); const textureAsset = new Texture2D(); - textureAsset.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - textureAsset.setMipFilter(Texture2D.Filter.NONE); - textureAsset.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE); + textureAsset.setFilters(Filter.NEAREST, Filter.NEAREST); + textureAsset.setMipFilter(Filter.NONE); + textureAsset.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); textureAsset.image = image; if (!textureAsset.getGFXTexture()) { warnID(16375); diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index 7fbe7c25679..1fbefc14ecc 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -37,7 +37,7 @@ import { MorphRenderingInstance } from '../assets/morph-rendering'; import { NodeEventType } from '../../scene-graph/node-event'; import { Texture } from '../../gfx'; import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; -import { settings, Settings } from '../../core/settings'; +import { settings, SettingsCategory } from '../../core/settings'; import { ReflectionProbeType } from '../reflection-probe/reflection-probe-enum'; import { getPhaseID } from '../../rendering/pass-phase'; import { SubModel } from '../../render-scene/scene'; @@ -95,6 +95,26 @@ const ModelShadowReceivingMode = Enum({ ON: 1, }); +enum ModelBakeSettingsEvent { + /** + * @en The event which will be triggered when the useLightProbe is changed. + * @zh useLightProbe属性修改时触发的事件 + */ + USE_LIGHT_PROBE_CHANGED = 'use_light_probe_changed', + + /** + * @en The event which will be triggered when the reflectionProbe is changed. + * @zh reflectionProbe 属性修改时触发的事件 + */ + REFLECTION_PROBE_CHANGED = 'reflection_probe_changed', + + /** + * @en The event which will be triggered when the bakeToReflectionProbe is changed. + * @zh bakeToReflectionProbe 属性修改时触发的事件 + */ + BAKE_TO_REFLECTION_PROBE_CHANGED = 'bake_to_reflection_probe_changed', +} + /** * @en Model's bake settings. * @zh 模型烘焙设置 @@ -105,19 +125,19 @@ class ModelBakeSettings extends EventTarget { * @en The event which will be triggered when the useLightProbe is changed. * @zh useLightProbe属性修改时触发的事件 */ - public static readonly USE_LIGHT_PROBE_CHANGED = 'use_light_probe_changed'; + public static readonly USE_LIGHT_PROBE_CHANGED = ModelBakeSettingsEvent.USE_LIGHT_PROBE_CHANGED; /** * @en The event which will be triggered when the reflectionProbe is changed. * @zh reflectionProbe 属性修改时触发的事件 */ - public static readonly REFLECTION_PROBE_CHANGED = 'reflection_probe_changed'; + public static readonly REFLECTION_PROBE_CHANGED = ModelBakeSettingsEvent.REFLECTION_PROBE_CHANGED; /** * @en The event which will be triggered when the bakeToReflectionProbe is changed. * @zh bakeToReflectionProbe 属性修改时触发的事件 */ - public static readonly BAKE_TO_REFLECTION_PROBE_CHANGED = 'bake_to_reflection_probe_changed'; + public static readonly BAKE_TO_REFLECTION_PROBE_CHANGED = ModelBakeSettingsEvent.BAKE_TO_REFLECTION_PROBE_CHANGED; @serializable public texture: Texture2D|null = null; @@ -223,7 +243,7 @@ class ModelBakeSettings extends EventTarget { set useLightProbe (val) { this._useLightProbe = val; - this.emit(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED); + this.emit(ModelBakeSettingsEvent.USE_LIGHT_PROBE_CHANGED); } /** @@ -258,7 +278,7 @@ class ModelBakeSettings extends EventTarget { set reflectionProbe (val) { this._reflectionProbeType = val; - this.emit(ModelBakeSettings.REFLECTION_PROBE_CHANGED); + this.emit(ModelBakeSettingsEvent.REFLECTION_PROBE_CHANGED); } /** @@ -273,7 +293,7 @@ class ModelBakeSettings extends EventTarget { set bakeToReflectionProbe (val) { this._bakeToReflectionProbe = val; - this.emit(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED); + this.emit(ModelBakeSettingsEvent.BAKE_TO_REFLECTION_PROBE_CHANGED); } } @@ -543,7 +563,7 @@ export class MeshRenderer extends ModelRenderer { constructor () { super(); - const highQualityMode = settings.querySettings(Settings.Category.RENDERING, 'highQualityMode'); + const highQualityMode = settings.querySettings(SettingsCategory.RENDERING, 'highQualityMode'); if (highQualityMode) { this._shadowCastingMode = ModelShadowCastingMode.ON; this.bakeSettings.castShadow = true; @@ -590,9 +610,9 @@ export class MeshRenderer extends ModelRenderer { super.onEnable(); this.node.on(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this); this.node.on(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this); - this.bakeSettings.on(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this); - this.bakeSettings.on(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this); - this.bakeSettings.on(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this); + this.bakeSettings.on(ModelBakeSettingsEvent.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this); + this.bakeSettings.on(ModelBakeSettingsEvent.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this); + this.bakeSettings.on(ModelBakeSettingsEvent.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this); if (!this._model) { this._updateModels(); @@ -619,9 +639,9 @@ export class MeshRenderer extends ModelRenderer { } this.node.off(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this); this.node.off(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this); - this.bakeSettings.off(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this); - this.bakeSettings.off(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this); - this.bakeSettings.off(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this); + this.bakeSettings.off(ModelBakeSettingsEvent.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this); + this.bakeSettings.off(ModelBakeSettingsEvent.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this); + this.bakeSettings.off(ModelBakeSettingsEvent.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this); } public onDestroy (): void { diff --git a/cocos/3d/lights/directional-light-component.ts b/cocos/3d/lights/directional-light-component.ts index 5e46460f578..72a6275d93a 100644 --- a/cocos/3d/lights/directional-light-component.ts +++ b/cocos/3d/lights/directional-light-component.ts @@ -25,7 +25,7 @@ import { Light } from './light-component'; import { scene } from '../../render-scene'; -import { cclegacy, clamp, warnID, CCBoolean, CCFloat, _decorator, settings, Settings, CCInteger } from '../../core'; +import { cclegacy, clamp, warnID, CCBoolean, CCFloat, _decorator, settings, CCInteger, SettingsCategory } from '../../core'; import { Camera, PCFType, Shadows, ShadowType, CSMOptimizationMode, CSMLevel } from '../../render-scene/scene'; import { Root } from '../../root'; import { MeshRenderer } from '../framework/mesh-renderer'; @@ -520,7 +520,7 @@ export class DirectionalLight extends Light { super(); this._lightType = scene.DirectionalLight; - const highQualityMode = settings.querySettings(Settings.Category.RENDERING, 'highQualityMode'); + const highQualityMode = settings.querySettings(SettingsCategory.RENDERING, 'highQualityMode'); if (highQualityMode) { this._shadowPcf = PCFType.SOFT_2X; diff --git a/cocos/3d/models/skinning-model.ts b/cocos/3d/models/skinning-model.ts index 3ebd761b052..f74c7b6cbc1 100644 --- a/cocos/3d/models/skinning-model.ts +++ b/cocos/3d/models/skinning-model.ts @@ -36,7 +36,7 @@ import { MorphModel } from './morph-model'; import { deleteTransform, getTransform, getWorldMatrix, IJointTransform } from '../../animation/skeletal-animation-utils'; import { IMacroPatch, BatchingSchemes, Pass } from '../../render-scene'; import { director } from '../../game'; -import { PixelFormat } from '../../asset/assets/asset-enum'; +import { Filter, PixelFormat, WrapMode } from '../../asset/assets/asset-enum'; import { Texture2D, ImageAsset } from '../../asset/assets'; import { SubModel } from '../../render-scene/scene'; @@ -126,7 +126,7 @@ export class SkinningModel extends MorphModel { * @en Abstract function for [[BakedSkinningModel]], empty implementation. * @zh 由 [[BakedSkinningModel]] 继承的空函数。 */ - public uploadAnimation () : void {} + public uploadAnimation (): void {} /** * @en Bind the skeleton with its skinning root node and the mesh data. @@ -332,9 +332,9 @@ export class SkinningModel extends MorphModel { format: pixelFormat, }); const texture = new Texture2D(); - texture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - texture.setMipFilter(Texture2D.Filter.NONE); - texture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE); + texture.setFilters(Filter.NEAREST, Filter.NEAREST); + texture.setMipFilter(Filter.NONE); + texture.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); texture.image = image; textures[i] = texture; } diff --git a/cocos/3d/reflection-probe/reflection-probe-manager.ts b/cocos/3d/reflection-probe/reflection-probe-manager.ts index c4ac433ee71..6a8e788dc48 100644 --- a/cocos/3d/reflection-probe/reflection-probe-manager.ts +++ b/cocos/3d/reflection-probe/reflection-probe-manager.ts @@ -23,11 +23,10 @@ THE SOFTWARE. */ -import { EDITOR } from 'internal:constants'; import { MeshRenderer } from '../framework/mesh-renderer'; import { ReflectionProbeType } from './reflection-probe-enum'; import { ImageAsset, Texture2D } from '../../asset/assets'; -import { PixelFormat } from '../../asset/assets/asset-enum'; +import { Filter, PixelFormat, WrapMode } from '../../asset/assets/asset-enum'; import { Vec3, geometry, cclegacy } from '../../core'; import { AABB } from '../../core/geometry'; import { Texture } from '../../gfx'; @@ -429,9 +428,9 @@ export class ReflectionProbeManager { }); this._dataTexture = new Texture2D(); - this._dataTexture.setFilters(Texture2D.Filter.NONE, Texture2D.Filter.NONE); - this._dataTexture.setMipFilter(Texture2D.Filter.NONE); - this._dataTexture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE); + this._dataTexture.setFilters(Filter.NONE, Filter.NONE); + this._dataTexture.setMipFilter(Filter.NONE); + this._dataTexture.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); this._dataTexture.image = image; this._dataTexture.uploadData(updateView); diff --git a/cocos/animation/animation-component.ts b/cocos/animation/animation-component.ts index ced9b78886e..f4ee1e88d1f 100644 --- a/cocos/animation/animation-component.ts +++ b/cocos/animation/animation-component.ts @@ -27,7 +27,7 @@ import { EDITOR_NOT_IN_PREVIEW, TEST } from 'internal:constants'; import { Component } from '../scene-graph/component'; import { Eventify, warnID, js, cclegacy } from '../core'; import { AnimationClip } from './animation-clip'; -import { AnimationState, EventType } from './animation-state'; +import { AnimationState, AnimationStateEventType } from './animation-state'; import { CrossFade } from './cross-fade'; /** @@ -118,7 +118,7 @@ export class Animation extends Eventify(Component) { } } - public static EventType = EventType; + public static EventType = AnimationStateEventType; /** * @en @@ -388,17 +388,17 @@ export class Animation extends Eventify(Component) { * animation.on('play', this.onPlay, this); * ``` */ - public on void> (type: EventType, callback: TFunction, thisArg?: any, once?: boolean): TFunction { + public on void> (type: AnimationStateEventType, callback: TFunction, thisArg?: any, once?: boolean): TFunction { const ret = super.on(type, callback, thisArg, once); - if (type === EventType.LASTFRAME) { + if (type === AnimationStateEventType.LASTFRAME) { this._syncAllowLastFrameEvent(); } return ret; } - public once void> (type: EventType, callback: TFunction, thisArg?: any): TFunction { + public once void> (type: AnimationStateEventType, callback: TFunction, thisArg?: any): TFunction { const ret = super.once(type, callback, thisArg); - if (type === EventType.LASTFRAME) { + if (type === AnimationStateEventType.LASTFRAME) { this._syncAllowLastFrameEvent(); } return ret; @@ -418,9 +418,9 @@ export class Animation extends Eventify(Component) { * animation.off('play', this.onPlay, this); * ``` */ - public off (type: EventType, callback?: (...any) => void, thisArg?: any): void { + public off (type: AnimationStateEventType, callback?: (...any) => void, thisArg?: any): void { super.off(type, callback, thisArg); - if (type === EventType.LASTFRAME) { + if (type === AnimationStateEventType.LASTFRAME) { this._syncDisallowLastFrameEvent(); } } @@ -438,7 +438,7 @@ export class Animation extends Eventify(Component) { protected _doCreateState (clip: AnimationClip, name: string): AnimationState { const state = this._createState(clip, name); state._setEventTarget(this); - state.allowLastFrameEvent(this.hasEventListener(EventType.LASTFRAME)); + state.allowLastFrameEvent(this.hasEventListener(AnimationStateEventType.LASTFRAME)); if (this.node) { state.initialize(this.node); } @@ -465,7 +465,7 @@ export class Animation extends Eventify(Component) { } private _syncAllowLastFrameEvent (): void { - if (this.hasEventListener(EventType.LASTFRAME)) { + if (this.hasEventListener(AnimationStateEventType.LASTFRAME)) { for (const stateName in this._nameToState) { this._nameToState[stateName].allowLastFrameEvent(true); } @@ -473,7 +473,7 @@ export class Animation extends Eventify(Component) { } private _syncDisallowLastFrameEvent (): void { - if (!this.hasEventListener(EventType.LASTFRAME)) { + if (!this.hasEventListener(AnimationStateEventType.LASTFRAME)) { for (const stateName in this._nameToState) { this._nameToState[stateName].allowLastFrameEvent(false); } @@ -481,7 +481,7 @@ export class Animation extends Eventify(Component) { } } -type EventType_ = EventType; +type EventType_ = AnimationStateEventType; export declare namespace Animation { export type EventType = EventType_; diff --git a/cocos/animation/animation-manager.ts b/cocos/animation/animation-manager.ts index eb1f32e28e5..a524f38637a 100644 --- a/cocos/animation/animation-manager.ts +++ b/cocos/animation/animation-manager.ts @@ -24,7 +24,7 @@ import { ccclass } from 'cc.decorator'; import { System, errorID, cclegacy, js } from '../core'; -import { director, Director } from '../game/director'; +import { director, Director, DirectorEvent } from '../game/director'; import { Node } from '../scene-graph'; import { LegacyBlendStateBuffer } from '../3d/skeletal-animation/skeletal-animation-blending'; import { AnimationState } from './animation-state'; @@ -160,7 +160,7 @@ export class AnimationManager extends System { } } -director.on(Director.EVENT_INIT, (): void => { +director.on(DirectorEvent.INIT, (): void => { const animationManager = new AnimationManager(); director.registerSystem(AnimationManager.ID, animationManager, System.Priority.HIGH); }); diff --git a/cocos/animation/animation-state.ts b/cocos/animation/animation-state.ts index 31ca4d8ac7f..11fcd4f139e 100644 --- a/cocos/animation/animation-state.ts +++ b/cocos/animation/animation-state.ts @@ -37,7 +37,7 @@ import { getGlobalAnimationManager } from './global-animation-manager'; * @en The event type supported by Animation * @zh Animation 支持的事件类型。 */ -export enum EventType { +export enum AnimationStateEventType { /** * @en Emit when begin playing animation * @zh 开始播放时触发。 @@ -71,7 +71,7 @@ export enum EventType { */ FINISHED = 'finished', } -ccenum(EventType); +ccenum(AnimationStateEventType); /** * @en @@ -516,7 +516,7 @@ export class AnimationState extends Playable { this.setTime(this._getPlaybackStart()); this._delayTime = this._delay; this._onReplayOrResume(); - this.emit(EventType.PLAY, this); + this.emit(AnimationStateEventType.PLAY, this); this._clipEmbeddedPlayerEval?.notifyHostPlay(this.current); } @@ -524,19 +524,19 @@ export class AnimationState extends Playable { if (!this.isPaused) { this._onPauseOrStop(); } - this.emit(EventType.STOP, this); + this.emit(AnimationStateEventType.STOP, this); this._clipEmbeddedPlayerEval?.notifyHostStop(); } protected onResume (): void { this._onReplayOrResume(); - this.emit(EventType.RESUME, this); + this.emit(AnimationStateEventType.RESUME, this); this._clipEmbeddedPlayerEval?.notifyHostPlay(this.current); } protected onPause (): void { this._onPauseOrStop(); - this.emit(EventType.PAUSE, this); + this.emit(AnimationStateEventType.PAUSE, this); this._clipEmbeddedPlayerEval?.notifyHostPause(this.current); } @@ -574,7 +574,7 @@ export class AnimationState extends Playable { } if (this.repeatCount > 1 && ((info.iterations | 0) > (lastInfo.iterations | 0))) { - this.emit(EventType.LASTFRAME, this); + this.emit(AnimationStateEventType.LASTFRAME, this); } lastInfo.set(info); @@ -582,7 +582,7 @@ export class AnimationState extends Playable { if (info.stopped) { this.stop(); - this.emit(EventType.FINISHED, this); + this.emit(AnimationStateEventType.FINISHED, this); } } @@ -617,7 +617,7 @@ export class AnimationState extends Playable { } if ((this.time > 0 && this._lastIterations > ratio) || (this.time < 0 && this._lastIterations < ratio)) { - this.emit(EventType.LASTFRAME, this); + this.emit(AnimationStateEventType.LASTFRAME, this); } this._lastIterations = ratio; diff --git a/cocos/asset/asset-manager/asset-manager.ts b/cocos/asset/asset-manager/asset-manager.ts index e9ce3a3a780..9b593bb4caf 100644 --- a/cocos/asset/asset-manager/asset-manager.ts +++ b/cocos/asset/asset-manager/asset-manager.ts @@ -25,7 +25,7 @@ import { BUILD, EDITOR, PREVIEW } from 'internal:constants'; import { Asset } from '../assets/asset'; -import { error, sys, Settings, settings, path, cclegacy, EventTarget } from '../../core'; +import { error, settings, path, cclegacy, EventTarget, SettingsCategory } from '../../core'; import Bundle from './bundle'; import Cache, { ICache } from './cache'; import CacheManager from './cache-manager'; @@ -308,12 +308,12 @@ export class AssetManager { public references = references; private _releaseManager = releaseManager; - private _files = files; - private _parsed = parsed; - private _parsePipeline = BUILD ? null : new Pipeline('parse existing json', [this.loadPipe]); - private _projectBundles: string[] = []; + private _files$ = files; + private _parsed$ = parsed; + private _parsePipeline$ = BUILD ? null : new Pipeline('parse existing json', [this.loadPipe]); + private _projectBundles$: string[] = []; private static _instance: AssetManager; - private _eventTarget = new EventTarget(); + private _eventTarget$ = new EventTarget(); /** * @en @@ -367,7 +367,7 @@ export class AssetManager { * @engineInternal */ public onAssetMissing (func: (parentAsset: Asset, owner: any, propName: string, uuid: string) => void, target?: any): void { - this._eventTarget.on(EVENT_ASSET_MISSING, func, target); + this._eventTarget$.on(EVENT_ASSET_MISSING, func, target); } /** @@ -381,7 +381,7 @@ export class AssetManager { * @engineInternal */ public offAssetMissing (func: (parentAsset: Asset, owner: any, propName: string, uuid: string) => void, target?: any): void { - this._eventTarget.off(EVENT_ASSET_MISSING, func, target); + this._eventTarget$.off(EVENT_ASSET_MISSING, func, target); } /** @@ -397,7 +397,7 @@ export class AssetManager { * @engineInternal */ public dispatchAssetMissing (parentAsset: Asset, owner: any, propName: string, uuid: string): void { - this._eventTarget.emit(EVENT_ASSET_MISSING, parentAsset, owner, propName, uuid); + this._eventTarget$.emit(EVENT_ASSET_MISSING, parentAsset, owner, propName, uuid); } /** @@ -412,16 +412,16 @@ export class AssetManager { * @internal */ public init (options: IAssetManagerOptions = {}): void { - const server = options.server || settings.querySettings(Settings.Category.ASSETS, 'server') || ''; - const bundleVers = options.bundleVers || settings.querySettings(Settings.Category.ASSETS, 'bundleVers') || {}; - const remoteBundles = options.remoteBundles || settings.querySettings(Settings.Category.ASSETS, 'remoteBundles') || []; - const downloadMaxConcurrency = options.downloadMaxConcurrency || settings.querySettings(Settings.Category.ASSETS, 'downloadMaxConcurrency'); + const server = options.server || settings.querySettings(SettingsCategory.ASSETS, 'server') || ''; + const bundleVers = options.bundleVers || settings.querySettings(SettingsCategory.ASSETS, 'bundleVers') || {}; + const remoteBundles = options.remoteBundles || settings.querySettings(SettingsCategory.ASSETS, 'remoteBundles') || []; + const downloadMaxConcurrency = options.downloadMaxConcurrency || settings.querySettings(SettingsCategory.ASSETS, 'downloadMaxConcurrency'); if (downloadMaxConcurrency && downloadMaxConcurrency > 0) { this.downloader.maxConcurrency = downloadMaxConcurrency; } - this._files.clear(); - this._parsed.clear(); + this._files$.clear(); + this._parsed$.clear(); this._releaseManager.init(); this.assets.clear(); this.bundles.clear(); @@ -429,18 +429,18 @@ export class AssetManager { this.downloader.init(server, bundleVers, remoteBundles); this.parser.init(); this.dependUtil.init(); - let importBase = options.importBase || settings.querySettings(Settings.Category.ASSETS, 'importBase') || ''; + let importBase = options.importBase || settings.querySettings(SettingsCategory.ASSETS, 'importBase') || ''; if (importBase && importBase.endsWith('/')) { importBase = importBase.substr(0, importBase.length - 1); } - let nativeBase = options.nativeBase || settings.querySettings(Settings.Category.ASSETS, 'nativeBase') || ''; + let nativeBase = options.nativeBase || settings.querySettings(SettingsCategory.ASSETS, 'nativeBase') || ''; if (nativeBase && nativeBase.endsWith('/')) { nativeBase = nativeBase.substr(0, nativeBase.length - 1); } this.generalImportBase = importBase; this.generalNativeBase = nativeBase; - this._projectBundles = settings.querySettings(Settings.Category.ASSETS, 'projectBundles') || []; - const assetsOverride = settings.querySettings(Settings.Category.ASSETS, 'assetsOverrides') || {}; + this._projectBundles$ = settings.querySettings(SettingsCategory.ASSETS, 'projectBundles') || []; + const assetsOverride = settings.querySettings(SettingsCategory.ASSETS, 'assetsOverrides') || {}; for (const key in assetsOverride) { this.assetsOverrideMap.set(key, assetsOverride[key] as string); } @@ -813,7 +813,7 @@ export class AssetManager { if (onComp) { onComp(err, data); } }), }); - this._parsePipeline!.async(task); + this._parsePipeline$!.async(task); } } diff --git a/cocos/asset/asset-manager/builtin-res-mgr.jsb.ts b/cocos/asset/asset-manager/builtin-res-mgr.jsb.ts index 582fe6717b8..d58697a2363 100644 --- a/cocos/asset/asset-manager/builtin-res-mgr.jsb.ts +++ b/cocos/asset/asset-manager/builtin-res-mgr.jsb.ts @@ -31,6 +31,7 @@ import Bundle from '../asset-manager/bundle'; import { Settings, settings, cclegacy } from '../../core'; import { releaseManager } from '../asset-manager/release-manager'; import type { BuiltinResMgr as JsbBuiltinResMgr } from './builtin-res-mgr'; +import { PixelFormat } from '../assets/asset-enum'; declare const jsb: any; @@ -61,7 +62,7 @@ builtinResMgrProto.init = function () { height: len, _data: blackValueView, _compressed: false, - format: Texture2D.PixelFormat.RGBA8888, + format: PixelFormat.RGBA8888, }; // black texture diff --git a/cocos/asset/asset-manager/builtin-res-mgr.ts b/cocos/asset/asset-manager/builtin-res-mgr.ts index 4ce58cdd83b..cbd0991fbae 100644 --- a/cocos/asset/asset-manager/builtin-res-mgr.ts +++ b/cocos/asset/asset-manager/builtin-res-mgr.ts @@ -31,9 +31,10 @@ import { TextureCube } from '../assets/texture-cube'; import assetManager from './asset-manager'; import { BuiltinBundleName } from './shared'; import Bundle from './bundle'; -import { Settings, settings, cclegacy } from '../../core'; +import { settings, cclegacy, SettingsCategory } from '../../core'; import { releaseManager } from './release-manager'; import { Material } from '../assets'; +import { Filter, PixelFormat } from '../assets/asset-enum'; export class BuiltinResMgr { protected _resources: Record = {}; @@ -124,7 +125,7 @@ export class BuiltinResMgr { height: len, _data: blackValueView, _compressed: false, - format: Texture2D.PixelFormat.RGBA8888, + format: PixelFormat.RGBA8888, }; const emptyMemImageSource: ImageSource = { @@ -132,7 +133,7 @@ export class BuiltinResMgr { height: len, _data: emptyValueView, _compressed: false, - format: Texture2D.PixelFormat.RGBA8888, + format: PixelFormat.RGBA8888, }; const greyMemImageSource: ImageSource = { @@ -140,7 +141,7 @@ export class BuiltinResMgr { height: len, _data: greyValueView, _compressed: false, - format: Texture2D.PixelFormat.RGBA8888, + format: PixelFormat.RGBA8888, }; const whiteMemImageSource: ImageSource = { @@ -148,7 +149,7 @@ export class BuiltinResMgr { height: len, _data: whiteValueView, _compressed: false, - format: Texture2D.PixelFormat.RGBA8888, + format: PixelFormat.RGBA8888, }; const normalMemImageSource: ImageSource = { @@ -156,7 +157,7 @@ export class BuiltinResMgr { height: len, _data: normalValueView, _compressed: false, - format: Texture2D.PixelFormat.RGBA8888, + format: PixelFormat.RGBA8888, }; const defaultMemImageSource: ImageSource = { @@ -164,7 +165,7 @@ export class BuiltinResMgr { height: defaultSize, _data: defaultValueView, _compressed: false, - format: Texture2D.PixelFormat.RGBA8888, + format: PixelFormat.RGBA8888, }; // ============================ @@ -189,7 +190,7 @@ export class BuiltinResMgr { // black cube texture const blackCubeTexture = new TextureCube(); blackCubeTexture._uuid = 'black-cube-texture'; - blackCubeTexture.setMipFilter(TextureCube.Filter.NEAREST); + blackCubeTexture.setMipFilter(Filter.NEAREST); blackCubeTexture.image = { front: new ImageAsset(blackMemImageSource), back: new ImageAsset(blackMemImageSource), @@ -210,7 +211,7 @@ export class BuiltinResMgr { // grey cube texture const greyCubeTexture = new TextureCube(); greyCubeTexture._uuid = 'grey-cube-texture'; - greyCubeTexture.setMipFilter(TextureCube.Filter.NEAREST); + greyCubeTexture.setMipFilter(Filter.NEAREST); greyCubeTexture.image = { front: new ImageAsset(greyMemImageSource), back: new ImageAsset(greyMemImageSource), @@ -231,7 +232,7 @@ export class BuiltinResMgr { // white cube texture const whiteCubeTexture = new TextureCube(); whiteCubeTexture._uuid = 'white-cube-texture'; - whiteCubeTexture.setMipFilter(TextureCube.Filter.NEAREST); + whiteCubeTexture.setMipFilter(Filter.NEAREST); whiteCubeTexture.image = { front: new ImageAsset(whiteMemImageSource), back: new ImageAsset(whiteMemImageSource), @@ -258,7 +259,7 @@ export class BuiltinResMgr { // default cube texture const defaultCubeTexture = new TextureCube(); - defaultCubeTexture.setMipFilter(TextureCube.Filter.NEAREST); + defaultCubeTexture.setMipFilter(Filter.NEAREST); defaultCubeTexture._uuid = 'default-cube-texture'; defaultCubeTexture.image = { front: new ImageAsset(defaultMemImageSource), @@ -281,7 +282,7 @@ export class BuiltinResMgr { } if (EDITOR) { - const builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets'); + const builtinAssets = settings.querySettings(SettingsCategory.ENGINE, 'builtinAssets'); const builtinBundle = new Bundle(); builtinBundle.init({ name: BuiltinBundleName.INTERNAL, @@ -314,7 +315,7 @@ export class BuiltinResMgr { * @internal */ public loadBuiltinAssets (): Promise { - const builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets'); + const builtinAssets = settings.querySettings(SettingsCategory.ENGINE, 'builtinAssets'); if (TEST || !builtinAssets) return Promise.resolve(); const resources = this._resources; return new Promise((resolve, reject): void => { diff --git a/cocos/asset/asset-manager/bundle.ts b/cocos/asset/asset-manager/bundle.ts index 149adc0e376..72b8a8349ac 100644 --- a/cocos/asset/asset-manager/bundle.ts +++ b/cocos/asset/asset-manager/bundle.ts @@ -41,14 +41,14 @@ import { parseLoadResArgs, parseParameters } from './utilities'; * */ export default class Bundle { - private _config: Config = new Config(); + private _config$: Config = new Config(); /** * For internal use. * @engineInternal */ public get config (): Config { - return this._config; + return this._config$; } /** @@ -60,7 +60,7 @@ export default class Bundle { * */ public get name (): string { - return this._config.name; + return this._config$.name; } /** @@ -72,7 +72,7 @@ export default class Bundle { * */ public get deps (): string[] { - return this._config.deps!; + return this._config$.deps!; } /** @@ -84,7 +84,7 @@ export default class Bundle { * */ public get base (): string { - return this._config.base; + return this._config$.base; } /** @@ -103,7 +103,7 @@ export default class Bundle { * */ public getInfoWithPath (path: string, type?: Constructor | null): IAddressableInfo | null { - return this._config.getInfoWithPath(path, type); + return this._config$.getInfoWithPath(path, type); } /** @@ -125,7 +125,7 @@ export default class Bundle { * bundle.getDirWithPath('images', Texture2D, infos); */ public getDirWithPath (path: string, type?: Constructor | null, out?: IAddressableInfo[]): IAddressableInfo[] { - return this._config.getDirWithPath(path, type, out); + return this._config$.getDirWithPath(path, type, out); } /** @@ -143,7 +143,7 @@ export default class Bundle { * */ public getAssetInfo (uuid: string): IAssetInfo | null { - return this._config.getAssetInfo(uuid); + return this._config$.getAssetInfo(uuid); } /** @@ -161,7 +161,7 @@ export default class Bundle { * */ public getSceneInfo (name: string): ISceneInfo | null { - return this._config.getSceneInfo(name); + return this._config$.getSceneInfo(name); } /** @@ -176,7 +176,7 @@ export default class Bundle { * */ public init (options: IConfigOption): void { - this._config.init(options); + this._config$.init(options); bundles.add(options.name, this); } @@ -638,7 +638,7 @@ export default class Bundle { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _destroy (): void { - this._config.destroy(); + this._config$.destroy(); } } diff --git a/cocos/asset/asset-manager/config.ts b/cocos/asset/asset-manager/config.ts index 1a4a0899332..6b1a8adefb0 100644 --- a/cocos/asset/asset-manager/config.ts +++ b/cocos/asset/asset-manager/config.ts @@ -250,12 +250,12 @@ export default class Config { this.name = options.name || ''; this.deps = options.deps || []; // init - this._initUuid(options.uuids); - this._initPath(options.paths); - this._initScene(options.scenes); - this._initPackage(options.packs); - this._initVersion(options.versions); - this._initRedirect(options.redirect); + this._initUuid$(options.uuids); + this._initPath$(options.paths); + this._initScene$(options.scenes); + this._initPackage$(options.packs); + this._initVersion$(options.versions); + this._initRedirect$(options.redirect); for (const ext in options.extensionMap) { if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) { continue; @@ -333,7 +333,7 @@ export default class Config { this.assetInfos.destroy(); } - private _initUuid (uuidList: string[]): void { + private _initUuid$ (uuidList: string[]): void { if (!uuidList) { return; } @@ -344,7 +344,7 @@ export default class Config { } } - private _initPath (pathList: Record): void { + private _initPath$ (pathList: Record): void { if (!pathList) { return; } const paths = this.paths; paths.clear(); @@ -369,7 +369,7 @@ export default class Config { } } - private _initScene (sceneList: Record): void { + private _initScene$ (sceneList: Record): void { if (!sceneList) { return; } const scenes = this.scenes; scenes.clear(); @@ -382,7 +382,7 @@ export default class Config { } } - private _initPackage (packageList: Record): void { + private _initPackage$ (packageList: Record): void { if (!packageList) { return; } const assetInfos = this.assetInfos; for (const packUuid in packageList) { @@ -407,7 +407,7 @@ export default class Config { } } - private _initVersion (versions: { import?: string[], native?: string[] }): void { + private _initVersion$ (versions: { import?: string[], native?: string[] }): void { if (!versions) { return; } const assetInfos = this.assetInfos; let entries = versions.import; @@ -428,7 +428,7 @@ export default class Config { } } - private _initRedirect (redirect: string[]): void { + private _initRedirect$ (redirect: string[]): void { if (!redirect) { return; } const assetInfos = this.assetInfos; for (let i = 0, l = redirect.length; i < l; i += 2) { diff --git a/cocos/asset/asset-manager/depend-util.ts b/cocos/asset/asset-manager/depend-util.ts index 8f826676aea..dbac4f235d7 100644 --- a/cocos/asset/asset-manager/depend-util.ts +++ b/cocos/asset/asset-manager/depend-util.ts @@ -143,7 +143,7 @@ export class DependUtil { public getDepsRecursively (uuid: string): string[] { const exclude = Object.create(null); const depends = []; - this._descend(uuid, exclude, depends); + this._descend$(uuid, exclude, depends); return depends; } @@ -184,12 +184,12 @@ export class DependUtil { // issue: https://github.com/cocos/cocos-engine/issues/14642 if (Array.isArray(json) && (!(BUILD || isCompiledJson(json)) || !hasNativeDep(json as any))) { out = { - deps: this._parseDepsFromJson(json), + deps: this._parseDepsFromJson$(json), }; } else { try { const asset = deserialize(json, { __uuid__: uuid }); - out = this._parseDepsFromAsset(asset); + out = this._parseDepsFromAsset$(asset); if (out.nativeDep) { out.nativeDep.uuid = uuid; } @@ -206,14 +206,14 @@ export class DependUtil { return out; } } - out = this._parseDepsFromAsset(json); + out = this._parseDepsFromAsset$(json); } // cache dependency list this._depends.add(uuid, out); return out; } - private _parseDepsFromAsset (asset: Asset): IDependencies { + private _parseDepsFromAsset$ (asset: Asset): IDependencies { const out: IDependencies = { deps: [], parsedFromExistAsset: true, @@ -232,20 +232,20 @@ export class DependUtil { return out; } - private _parseDepsFromJson (json: any[]): string[] { + private _parseDepsFromJson$ (json: any[]): string[] { const depends = parseUuidDependencies(json); depends.forEach((uuid, index): string => depends[index] = decodeUuid(uuid)); return depends; } - private _descend (uuid: string, exclude: Record, depends: string[]): void { + private _descend$ (uuid: string, exclude: Record, depends: string[]): void { const deps = this.getDeps(uuid); for (let i = 0; i < deps.length; i++) { const depend = deps[i]; if (!exclude[depend]) { exclude[depend] = true; depends.push(depend); - this._descend(depend, exclude, depends); + this._descend$(depend, exclude, depends); } } } diff --git a/cocos/asset/asset-manager/deprecated.ts b/cocos/asset/asset-manager/deprecated.ts index ed29f8cee5a..85c2ac29942 100644 --- a/cocos/asset/asset-manager/deprecated.ts +++ b/cocos/asset/asset-manager/deprecated.ts @@ -101,7 +101,7 @@ export class CCLoader { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _autoReleaseSetting: Record = Object.create(null); - private _parseLoadResArgs = parseLoadResArgs; + private _parseLoadResArgs$ = parseLoadResArgs; /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. @@ -302,13 +302,16 @@ export class CCLoader { completeCallback: LoadCompleteCallback, ): any; public loadRes ( - url: string, type?: Constructor | LoadCompleteCallback | LoadProgressCallback, + url: string, + type?: Constructor | LoadCompleteCallback | LoadProgressCallback, progressCallback?: LoadProgressCallback | LoadCompleteCallback, completeCallback?: LoadCompleteCallback, ): any { - const { type: _type, onProgress, onComplete } = this._parseLoadResArgs(type as any, + const { type: _type, onProgress, onComplete } = this._parseLoadResArgs$( +type as any, progressCallback as LoadProgressCallback, - completeCallback as LoadCompleteCallback); + completeCallback as LoadCompleteCallback, + ); const extname = path.extname(url); if (extname && !resources.getInfoWithPath(url, _type)) { // strip extname @@ -355,9 +358,11 @@ export class CCLoader { progressCallback?: LoadProgressCallback, completeCallback?: LoadCompleteCallback, ): void { - const { type: _type, onProgress, onComplete } = this._parseLoadResArgs>(type as any, + const { type: _type, onProgress, onComplete } = this._parseLoadResArgs$>( +type as any, progressCallback as LoadProgressCallback, - completeCallback as LoadCompleteCallback); + completeCallback as LoadCompleteCallback, + ); urls.forEach((url, i): void => { const extname = path.extname(url); if (extname && !resources.getInfoWithPath(url, _type)) { @@ -442,9 +447,11 @@ export class CCLoader { progressCallback?: LoadProgressCallback | LoadDirCompleteCallback, completeCallback?: LoadDirCompleteCallback, ): any { - const { type: _type, onProgress, onComplete } = this._parseLoadResArgs>(type as any, + const { type: _type, onProgress, onComplete } = this._parseLoadResArgs$>( +type as any, progressCallback as LoadProgressCallback, - completeCallback as LoadDirCompleteCallback); + completeCallback as LoadDirCompleteCallback, + ); resources.loadDir(url, _type, onProgress, (err, out): void => { let urls: string[] = []; if (!err) { @@ -534,7 +541,7 @@ export class CCLoader { */ public get md5Pipe (): { transformURL(url: string): string; - } { + } { return md5Pipe; } diff --git a/cocos/asset/asset-manager/downloader.ts b/cocos/asset/asset-manager/downloader.ts index fa87cb3fac9..034e197c3ac 100644 --- a/cocos/asset/asset-manager/downloader.ts +++ b/cocos/asset/asset-manager/downloader.ts @@ -194,7 +194,7 @@ export class Downloader { * */ public get remoteServerAddress (): string { - return this._remoteServerAddress; + return this._remoteServerAddress$; } /** @@ -273,7 +273,7 @@ export class Downloader { public _downloadJson = downloadJson; // default handler map - private _downloaders: Record = { + private _downloaders$: Record = { // Images '.png': downloadImage, '.jpg': downloadImage, @@ -320,28 +320,28 @@ export class Downloader { default: downloadText, }; - private _downloading = new Cache<((err: Error | null, data?: any) => void)[]>(); - private _queue: IDownloadRequest[] = []; - private _queueDirty = false; + private _downloading$ = new Cache<((err: Error | null, data?: any) => void)[]>(); + private _queue$: IDownloadRequest[] = []; + private _queueDirty$ = false; // the number of loading thread - private _totalNum = 0; + private _totalNum$ = 0; // the number of request that launched in this period - private _totalNumThisPeriod = 0; + private _totalNumThisPeriod$ = 0; // last time, if now - lastTime > period, refresh _totalNumThisPeriod. - private _lastDate = -1; + private _lastDate$ = -1; // if _totalNumThisPeriod equals max, move request to next period using setTimeOut. - private _checkNextPeriod = false; - private _remoteServerAddress = ''; - private _maxInterval = 1 / 30; + private _checkNextPeriod$ = false; + private _remoteServerAddress$ = ''; + private _maxInterval$ = 1 / 30; private static _instance: Downloader; /** * @engineInternal */ public init (remoteServerAddress = '', bundleVers: Record = {}, remoteBundles: string[] = []): void { - this._downloading.clear(); - this._queue.length = 0; - this._remoteServerAddress = remoteServerAddress; + this._downloading$.clear(); + this._queue$.length = 0; + this._remoteServerAddress$ = remoteServerAddress; this.bundleVers = bundleVers; this.remoteBundles = remoteBundles; } @@ -377,9 +377,9 @@ export class Downloader { handler?: (url: string, options: Record, onComplete: ((err: Error | null, data?: any) => void)) => void, ): void { if (typeof type === 'object') { - js.mixin(this._downloaders, type); + js.mixin(this._downloaders$, type); } else { - this._downloaders[type] = handler as DownloadHandler; + this._downloaders$[type] = handler as DownloadHandler; } } @@ -415,15 +415,15 @@ export class Downloader { return; } - const downloadCallbacks = this._downloading.get(id); + const downloadCallbacks = this._downloading$.get(id); if (downloadCallbacks) { downloadCallbacks.push(onComplete); - const request = this._queue.find((x): boolean => x.id === id); + const request = this._queue$.find((x): boolean => x.id === id); if (!request) { return; } const priority: number = options.priority || 0; if (request.priority < priority) { request.priority = priority; - this._queueDirty = true; + this._queueDirty$ = true; } return; } @@ -432,11 +432,11 @@ export class Downloader { const maxRetryCount = typeof options.maxRetryCount !== 'undefined' ? options.maxRetryCount as number : this.maxRetryCount; const maxConcurrency = typeof options.maxConcurrency !== 'undefined' ? options.maxConcurrency as number : this.maxConcurrency; const maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame as number : this.maxRequestsPerFrame; - const handler = this._downloaders[type] || this._downloaders.default; + const handler = this._downloaders$[type] || this._downloaders$.default; const process: RetryFunction = (index, callback): void => { if (index === 0) { - this._downloading.add(id, [onComplete]); + this._downloading$.add(id, [onComplete]); } if (!this.limited) { @@ -449,28 +449,28 @@ export class Downloader { const done: ((err: Error | null, data?: any) => void) = (err, data): void => { // when finish downloading, update _totalNum - this._totalNum--; + this._totalNum$--; this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame); callback(err, data); }; - if (this._totalNum < maxConcurrency && this._totalNumThisPeriod < maxRequestsPerFrame) { + if (this._totalNum$ < maxConcurrency && this._totalNumThisPeriod$ < maxRequestsPerFrame) { handler(urlAppendTimestamp(url, this.appendTimeStamp), options, done); - this._totalNum++; - this._totalNumThisPeriod++; + this._totalNum$++; + this._totalNumThisPeriod$++; } else { // when number of request up to limitation, cache the rest - this._queue.push({ id, priority: options.priority || 0, url, options, done, handler }); - this._queueDirty = true; + this._queue$.push({ id, priority: options.priority || 0, url, options, done, handler }); + this._queueDirty$ = true; - if (this._totalNum < maxConcurrency) { this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame); } + if (this._totalNum$ < maxConcurrency) { this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame); } } }; // when retry finished, invoke callbacks const finale = (err: Error | null, result: any): void => { if (!err) { files.add(id, result); } - const callbacks = this._downloading.remove(id) as ((err: Error | null, data?: any) => void)[]; + const callbacks = this._downloading$.remove(id) as ((err: Error | null, data?: any) => void)[]; for (let i = 0, l = callbacks.length; i < l; i++) { callbacks[i](err, result); } @@ -498,28 +498,28 @@ export class Downloader { const now = performance.now(); // use deltaTime as interval const deltaTime = cclegacy.game.deltaTime; - const interval = deltaTime > this._maxInterval ? this._maxInterval : deltaTime; - if (now - this._lastDate > interval * 1000) { - this._totalNumThisPeriod = 0; - this._lastDate = now; + const interval = deltaTime > this._maxInterval$ ? this._maxInterval$ : deltaTime; + if (now - this._lastDate$ > interval * 1000) { + this._totalNumThisPeriod$ = 0; + this._lastDate$ = now; } } // handle the rest request in next period private _handleQueue (maxConcurrency: number, maxRequestsPerFrame: number): void { - this._checkNextPeriod = false; + this._checkNextPeriod$ = false; this._updateTime(); - while (this._queue.length > 0 && this._totalNum < maxConcurrency && this._totalNumThisPeriod < maxRequestsPerFrame) { - if (this._queueDirty) { - this._queue.sort((a, b): number => a.priority - b.priority); - this._queueDirty = false; + while (this._queue$.length > 0 && this._totalNum$ < maxConcurrency && this._totalNumThisPeriod$ < maxRequestsPerFrame) { + if (this._queueDirty$) { + this._queue$.sort((a, b): number => a.priority - b.priority); + this._queueDirty$ = false; } - const request = this._queue.pop(); + const request = this._queue$.pop(); if (!request) { break; } - this._totalNum++; - this._totalNumThisPeriod++; + this._totalNum$++; + this._totalNumThisPeriod$++; request.handler(urlAppendTimestamp(request.url, this.appendTimeStamp), request.options, request.done); } @@ -527,9 +527,9 @@ export class Downloader { } private _handleQueueInNextFrame (maxConcurrency: number, maxRequestsPerFrame: number): void { - if (!this._checkNextPeriod && this._queue.length > 0) { + if (!this._checkNextPeriod$ && this._queue$.length > 0) { misc.callInNextTick(this._handleQueue.bind(this), maxConcurrency, maxRequestsPerFrame); - this._checkNextPeriod = true; + this._checkNextPeriod$ = true; } } } diff --git a/cocos/asset/asset-manager/editor-path-replace.ts b/cocos/asset/asset-manager/editor-path-replace.ts index 970b855315a..10ac429dd0c 100644 --- a/cocos/asset/asset-manager/editor-path-replace.ts +++ b/cocos/asset/asset-manager/editor-path-replace.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ import { EDITOR, NATIVE, PREVIEW, TEST } from 'internal:constants'; -import { assert, Settings, settings } from '../../core'; +import { assert, settings, SettingsCategory } from '../../core'; import { fetchPipeline, pipeline } from './shared'; import Task from './task'; @@ -87,7 +87,7 @@ if ((EDITOR || PREVIEW) && !TEST) { } else { let previewServer = ''; if (NATIVE) { - previewServer = settings.querySettings(Settings.Category.PATH, 'previewServer') || ''; + previewServer = settings.querySettings(SettingsCategory.PATH, 'previewServer') || ''; assert(Boolean(previewServer)); } text = await fetchText(`${previewServer}/query-extname/${uuid}`) as string; diff --git a/cocos/asset/asset-manager/factory.ts b/cocos/asset/asset-manager/factory.ts index 3511ecb5d38..bf9df95fe0e 100644 --- a/cocos/asset/asset-manager/factory.ts +++ b/cocos/asset/asset-manager/factory.ts @@ -96,9 +96,9 @@ function createBundle (id: string, data: IConfigOption, options: Record void)[]>(); + private _creating$ = new Cache<((err: Error | null, data?: any | null) => void)[]>(); - private _producers: Record = { + private _producers$: Record = { // Images '.png': createImageAsset, '.jpg': createImageAsset, @@ -141,32 +141,32 @@ export class Factory { public register (type: string | Record, handler?: CreateHandler): void { if (typeof type === 'object') { - js.mixin(this._producers, type); + js.mixin(this._producers$, type); } else { - this._producers[type] = handler!; + this._producers$[type] = handler!; } } public create (id: string, data: any, type: string, options: Record, onComplete: ((err: Error | null, data?: Asset | Bundle | null) => void)): void { - const handler = this._producers[type] || this._producers.default; + const handler = this._producers$[type] || this._producers$.default; const asset = assets.get(id); if (!options.reloadAsset && asset) { onComplete(null, asset); return; } - const creating = this._creating.get(id); + const creating = this._creating$.get(id); if (creating) { creating.push(onComplete); return; } - this._creating.add(id, [onComplete]); + this._creating$.add(id, [onComplete]); handler(id, data, options, (err, result): void => { if (!err && result instanceof Asset) { result._uuid = id; cache(id, result, options.cacheAsset); } - const callbacks = this._creating.remove(id); + const callbacks = this._creating$.remove(id); for (let i = 0, l = callbacks!.length; i < l; i++) { callbacks![i](err, result); } diff --git a/cocos/asset/asset-manager/pack-manager.ts b/cocos/asset/asset-manager/pack-manager.ts index cab8fbc8aa7..cb2d88a6209 100644 --- a/cocos/asset/asset-manager/pack-manager.ts +++ b/cocos/asset/asset-manager/pack-manager.ts @@ -53,8 +53,8 @@ interface IUnpackRequest { * */ export class PackManager { - private _loading = new Cache(); - private _unpackers: Record = { + private _loading$ = new Cache(); + private _unpackers$: Record = { '.json': this.unpackJson, }; @@ -125,7 +125,7 @@ export class PackManager { } public init (): void { - this._loading.clear(); + this._loading$.clear(); } /** @@ -153,9 +153,9 @@ export class PackManager { public register (map: Record): void; public register (type: string | Record, handler?: Unpacker): void { if (typeof type === 'object') { - js.mixin(this._unpackers, type); + js.mixin(this._unpackers$, type); } else { - this._unpackers[type] = handler!; + this._unpackers$[type] = handler!; } } @@ -192,7 +192,7 @@ export class PackManager { onComplete(new Error('package data is wrong!')); return; } - const unpacker = this._unpackers[type]; + const unpacker = this._unpackers$[type]; unpacker(pack, data, options, onComplete); } @@ -232,10 +232,10 @@ export class PackManager { const packs = item.info.packs; // find a loading package - const loadingPack = packs.find((val): boolean => this._loading.has(val.uuid)); + const loadingPack = packs.find((val): boolean => this._loading$.has(val.uuid)); if (loadingPack) { - const req = this._loading.get(loadingPack.uuid); + const req = this._loading$.get(loadingPack.uuid); assertIsTrue(req); req.push({ onComplete, id: item.id }); return; @@ -243,7 +243,7 @@ export class PackManager { // download a new package const pack = packs[0]; - this._loading.add(pack.uuid, [{ onComplete, id: item.id }]); + this._loading$.add(pack.uuid, [{ onComplete, id: item.id }]); // find the url of pack assertIsTrue(item.config); @@ -261,7 +261,7 @@ export class PackManager { files.add(id, result[id]); } } - const callbacks = this._loading.remove(pack.uuid); + const callbacks = this._loading$.remove(pack.uuid); assertIsTrue(callbacks); for (let i = 0, l = callbacks.length; i < l; i++) { const cb = callbacks[i]; diff --git a/cocos/asset/asset-manager/parser.ts b/cocos/asset/asset-manager/parser.ts index fbda8052281..d64dbf3c7b1 100644 --- a/cocos/asset/asset-manager/parser.ts +++ b/cocos/asset/asset-manager/parser.ts @@ -43,9 +43,9 @@ export type ParseHandler = (file: any, options: Record, onComplete: * */ export class Parser { - private _parsing = new Cache<((err: Error | null, data?: any) => void)[]>(); + private _parsing$ = new Cache<((err: Error | null, data?: any) => void)[]>(); - private _parsers: Record = { + private _parsers$: Record = { '.png': this.parseImage, '.jpg': this.parseImage, '.bmp': this.parseImage, @@ -193,7 +193,7 @@ export class Parser { * @engineInternal */ public init (): void { - this._parsing.clear(); + this._parsing$.clear(); } /** @@ -234,9 +234,9 @@ export class Parser { ) => void, ): void { if (typeof type === 'object') { - js.mixin(this._parsers, type); + js.mixin(this._parsers$, type); } else { - this._parsers[type] = handler as ParseHandler; + this._parsers$[type] = handler as ParseHandler; } } @@ -273,26 +273,26 @@ export class Parser { onComplete(null, parsedAsset); return; } - const parsing = this._parsing.get(id); + const parsing = this._parsing$.get(id); if (parsing) { parsing.push(onComplete); return; } - const parseHandler = this._parsers[type]; + const parseHandler = this._parsers$[type]; if (!parseHandler) { onComplete(null, file); return; } - this._parsing.add(id, [onComplete]); + this._parsing$.add(id, [onComplete]); parseHandler(file, options, (err, data): void => { if (err) { files.remove(id); } else if (!isScene(data)) { parsed.add(id, data); } - const callbacks = this._parsing.remove(id); + const callbacks = this._parsing$.remove(id); for (let i = 0, l = callbacks!.length; i < l; i++) { callbacks![i](err, data); } diff --git a/cocos/asset/asset-manager/plist-parser.ts b/cocos/asset/asset-manager/plist-parser.ts index 5f240990996..4bd356d2e83 100644 --- a/cocos/asset/asset-manager/plist-parser.ts +++ b/cocos/asset/asset-manager/plist-parser.ts @@ -32,10 +32,10 @@ import { warnID } from '../../core'; * @class saxParser */ export class SAXParser { - private _parser: DOMParser | null = null; + private _parser$: DOMParser | null = null; constructor () { if (globalThis.DOMParser) { - this._parser = new DOMParser(); + this._parser$ = new DOMParser(); } } @@ -50,8 +50,8 @@ export class SAXParser { protected _parseXML (textxml: string): Document { // get a reference to the requested corresponding xml file - if (this._parser) { - return this._parser.parseFromString(textxml, 'text/xml'); + if (this._parser$) { + return this._parser$.parseFromString(textxml, 'text/xml'); } throw new Error('Dom parser is not supported in this platform!'); } @@ -86,16 +86,16 @@ class PlistParser extends SAXParser { break; } } - return this._parseNode(node!); + return this._parseNode$(node!); } - private _parseNode (node: HTMLElement): unknown { + private _parseNode$ (node: HTMLElement): unknown { let data: any = null; const tagName = node.tagName; if (tagName === 'dict') { - data = this._parseDict(node); + data = this._parseDict$(node); } else if (tagName === 'array') { - data = this._parseArray(node); + data = this._parseArray$(node); } else if (tagName === 'string') { if (node.childNodes.length === 1) { data = node.firstChild!.nodeValue; @@ -118,19 +118,19 @@ class PlistParser extends SAXParser { return data; } - private _parseArray (node: HTMLElement): unknown[] { + private _parseArray$ (node: HTMLElement): unknown[] { const data: any[] = []; for (let i = 0, len = node.childNodes.length; i < len; i++) { const child = node.childNodes[i]; if (child.nodeType !== 1) { continue; } - data.push(this._parseNode(child as HTMLElement)); + data.push(this._parseNode$(child as HTMLElement)); } return data; } - private _parseDict (node: HTMLElement): Record { + private _parseDict$ (node: HTMLElement): Record { const data = {}; let key = ''; for (let i = 0, len = node.childNodes.length; i < len; i++) { @@ -143,7 +143,7 @@ class PlistParser extends SAXParser { if (child.tagName === 'key') { key = child.firstChild!.nodeValue!; } else { - data[key] = this._parseNode(child); + data[key] = this._parseNode$(child); } // Parse the value node } return data; diff --git a/cocos/asset/asset-manager/release-manager.ts b/cocos/asset/asset-manager/release-manager.ts index 121af14ae55..6ebfe9052d9 100644 --- a/cocos/asset/asset-manager/release-manager.ts +++ b/cocos/asset/asset-manager/release-manager.ts @@ -113,18 +113,18 @@ function checkCircularReference (asset: Asset): number { } class ReleaseManager { - private _persistNodeDeps = new Cache(); - private _toDelete = new Cache(); - private _eventListener = false; - private _dontDestroyAssets: string[] = []; + private _persistNodeDeps$ = new Cache(); + private _toDelete$ = new Cache(); + private _eventListener$ = false; + private _dontDestroyAssets$: string[] = []; public addIgnoredAsset (asset: Asset): void { - this._dontDestroyAssets.push(asset._uuid); + this._dontDestroyAssets$.push(asset._uuid); } public init (): void { - this._persistNodeDeps.clear(); - this._toDelete.clear(); + this._persistNodeDeps$.clear(); + this._toDelete$.clear(); } /** @@ -139,23 +139,23 @@ class ReleaseManager { dependAsset.addRef(); } } - this._persistNodeDeps.add(node.uuid, deps); + this._persistNodeDeps$.add(node.uuid, deps); } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _removePersistNodeRef (node: Node): void { - if (!this._persistNodeDeps.has(node.uuid)) { return; } + if (!this._persistNodeDeps$.has(node.uuid)) { return; } - const deps = this._persistNodeDeps.get(node.uuid) as string[]; + const deps = this._persistNodeDeps$.get(node.uuid) as string[]; for (let i = 0, l = deps.length; i < l; i++) { const dependAsset = assets.get(deps[i]); if (dependAsset) { dependAsset.decRef(); } } - this._persistNodeDeps.remove(node.uuid); + this._persistNodeDeps$.remove(node.uuid); } // do auto release @@ -193,7 +193,7 @@ class ReleaseManager { if (sceneDeps) { sceneDeps.persistDeps = []; } for (const key in persistNodes) { const node = persistNodes[key]; - const deps = this._persistNodeDeps.get(node.uuid) as string[]; + const deps = this._persistNodeDeps$.get(node.uuid) as string[]; for (const dep of deps) { const dependAsset = assets.get(dep); if (dependAsset) { @@ -208,31 +208,31 @@ class ReleaseManager { public tryRelease (asset: Asset, force = false): void { if (!(asset instanceof Asset)) { return; } if (force) { - this._free(asset, force); + this._free$(asset, force); return; } - this._toDelete.add(asset._uuid, asset); + this._toDelete$.add(asset._uuid, asset); if (TEST) return; - if (!this._eventListener) { - this._eventListener = true; - misc.callInNextTick(this._freeAssets.bind(this)); + if (!this._eventListener$) { + this._eventListener$ = true; + misc.callInNextTick(this._freeAssets$.bind(this)); } } - private _freeAssets (): void { - this._eventListener = false; - this._toDelete.forEach((asset): void => { - this._free(asset); + private _freeAssets$ (): void { + this._eventListener$ = false; + this._toDelete$.forEach((asset): void => { + this._free$(asset); }); - this._toDelete.clear(); + this._toDelete$.clear(); } - private _free (asset: Asset, force = false): void { + private _free$ (asset: Asset, force = false): void { const uuid = asset._uuid; - this._toDelete.remove(uuid); + this._toDelete$.remove(uuid); - if (!isValid(asset, true) || this._dontDestroyAssets.indexOf(uuid) !== -1) { return; } + if (!isValid(asset, true) || this._dontDestroyAssets$.indexOf(uuid) !== -1) { return; } if (!force) { if (asset.refCount > 0) { @@ -249,7 +249,7 @@ class ReleaseManager { dependAsset.decRef(false); // no need to release dependencies recursively in editor if (!EDITOR) { - this._free(dependAsset, false); + this._free$(dependAsset, false); } } } diff --git a/cocos/asset/assets/asset-enum.ts b/cocos/asset/assets/asset-enum.ts index 0540b977746..2260500e516 100644 --- a/cocos/asset/assets/asset-enum.ts +++ b/cocos/asset/assets/asset-enum.ts @@ -22,10 +22,12 @@ THE SOFTWARE. */ -import { Address, Filter as GFXFilter, Format } from '../../gfx'; +import { Address, Filter, Format } from '../../gfx'; // define a specified number for the pixel format which gfx do not have a standard definition. -const CUSTOM_PIXEL_FORMAT = 1024; +enum CustomPixelFormat { + VALUE = 1024, +} /** * @en @@ -132,7 +134,7 @@ export enum PixelFormat { * @zh 包含 RGBA 通道的 PVR 2BPP 压缩纹理格式 * 这种压缩纹理格式贴图的高度是普通 RGB_PVRTC_2BPPV1 贴图高度的两倍,使用上半部分作为原始 RGB 通道数据,下半部分用来存储透明通道数据。 */ - RGB_A_PVRTC_2BPPV1 = CUSTOM_PIXEL_FORMAT, + RGB_A_PVRTC_2BPPV1 = CustomPixelFormat.VALUE, /** * @en A pixel format containing red, green, and blue channels that is PVR 4bpp compressed. * @zh 包含 RGB 通道的 PVR 4BPP 压缩纹理格式 @@ -150,7 +152,7 @@ export enum PixelFormat { * @zh 包含 RGBA 通道的 PVR 4BPP 压缩纹理格式 * 这种压缩纹理格式贴图的高度是普通 RGB_PVRTC_4BPPV1 贴图高度的两倍,使用上半部分作为原始 RGB 通道数据,下半部分用来存储透明通道数据。 */ - RGB_A_PVRTC_4BPPV1 = CUSTOM_PIXEL_FORMAT + 1, + RGB_A_PVRTC_4BPPV1 = CustomPixelFormat.VALUE + 1, /** * @en A pixel format containing red, green, and blue channels that is ETC1 compressed. * @zh 包含 RGB 通道的 ETC1 压缩纹理格式 @@ -160,7 +162,7 @@ export enum PixelFormat { * @en A pixel format containing red, green, blue, and alpha channels that is ETC1 compressed. * @zh 包含 RGBA 通道的 ETC1 压缩纹理格式 */ - RGBA_ETC1 = CUSTOM_PIXEL_FORMAT + 2, + RGBA_ETC1 = CustomPixelFormat.VALUE + 2, /** * @en A pixel format containing red, green, and blue channels that is ETC2 compressed. * @zh 包含 RGB 通道的 ETC2 压缩纹理格式 @@ -287,20 +289,22 @@ export enum WrapMode { * @zh * 纹理过滤模式。 */ -export enum Filter { - NONE = GFXFilter.NONE, +enum TextureFilter { + NONE = Filter.NONE, /** * @en * Specifies linear filtering. * @zh * 线性过滤模式。 */ - LINEAR = GFXFilter.LINEAR, + LINEAR = Filter.LINEAR, /** * @en * Specifies nearest filtering. * @zh * 临近过滤模式。 */ - NEAREST = GFXFilter.POINT, + NEAREST = Filter.POINT, } + +export { TextureFilter as Filter }; diff --git a/cocos/asset/assets/image-asset.ts b/cocos/asset/assets/image-asset.ts index 1840396f553..f20151cda14 100644 --- a/cocos/asset/assets/image-asset.ts +++ b/cocos/asset/assets/image-asset.ts @@ -547,13 +547,13 @@ export class ImageAsset extends Asset { @override get _nativeAsset (): any { // Maybe returned to pool in webgl. - return this._nativeData; + return this._nativeData$; } // TODO: Property 'format' does not exist on type 'ImageBitmap' // set _nativeAsset (value: ImageSource) { set _nativeAsset (value: any) { if (!(value instanceof HTMLElement) && !isImageBitmap(value)) { - value.format = value.format || this._format; + value.format = value.format || this._format$; } this.reset(value as ImageSource); } @@ -563,11 +563,11 @@ export class ImageAsset extends Asset { * @zh 此图像资源的图像数据。 */ get data (): ArrayBufferView | HTMLCanvasElement | HTMLImageElement | ImageBitmap | null { - if (isNativeImage(this._nativeData)) { - return this._nativeData; + if (isNativeImage(this._nativeData$)) { + return this._nativeData$; } - return this._nativeData && this._nativeData._data; + return this._nativeData$ && this._nativeData$._data; } /** @@ -575,7 +575,7 @@ export class ImageAsset extends Asset { * @zh 此图像资源的像素宽度。 */ get width (): number { - return this._nativeData.width || this._width; + return this._nativeData$.width || this._width$; } /** @@ -583,7 +583,7 @@ export class ImageAsset extends Asset { * @zh 此图像资源的像素高度。 */ get height (): number { - return this._nativeData.height || this._height; + return this._nativeData$.height || this._height$; } /** @@ -591,7 +591,7 @@ export class ImageAsset extends Asset { * @zh 此图像资源的像素格式。 */ get format (): PixelFormat { - return this._format; + return this._format$; } /** @@ -599,8 +599,8 @@ export class ImageAsset extends Asset { * @zh 此图像资源是否为压缩像素格式。 */ get isCompressed (): boolean { - return (this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12) - || (this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1); + return (this._format$ >= PixelFormat.RGB_ETC1 && this._format$ <= PixelFormat.RGBA_ASTC_12x12) + || (this._format$ >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format$ <= PixelFormat.RGBA_ETC1); } /** @@ -609,7 +609,7 @@ export class ImageAsset extends Asset { * @engineInternal */ get mipmapLevelDataSize (): number[] | undefined { - return (this._nativeData as IMemoryImageSource).mipmapLevelDataSize; + return (this._nativeData$ as IMemoryImageSource).mipmapLevelDataSize; } /** @@ -623,20 +623,21 @@ export class ImageAsset extends Asset { private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm', '.astc']; - private _nativeData: ImageSource; + private _nativeData$: ImageSource; + //NOTE: _exportedExts is used by editor, should not rename or mangle it. private _exportedExts: string[] | null | undefined = undefined; - private _format: PixelFormat = PixelFormat.RGBA8888; + private _format$: PixelFormat = PixelFormat.RGBA8888; - private _width = 0; + private _width$ = 0; - private _height = 0; + private _height$ = 0; constructor (nativeAsset?: ImageSource) { super(); - this._nativeData = { + this._nativeData$ = { _data: null, width: 0, height: 0, @@ -661,13 +662,13 @@ export class ImageAsset extends Asset { */ public reset (data: ImageSource): void { if (isImageBitmap(data)) { - this._nativeData = data; + this._nativeData$ = data; } else if (!(data instanceof HTMLElement)) { // this._nativeData = Object.create(data); - this._nativeData = data; - this._format = data.format; + this._nativeData$ = data; + this._format$ = data.format; } else { - this._nativeData = data; + this._nativeData$ = data; } } @@ -729,15 +730,15 @@ export class ImageAsset extends Asset { if (typeof data === 'string') { fmtStr = data; } else { - this._width = data.w; - this._height = data.h; + this._width$ = data.w; + this._height$ = data.h; fmtStr = data.fmt; } const device = _getGlobalDevice(); const extensionIDs = fmtStr.split('_'); let preferedExtensionIndex = Number.MAX_VALUE; - let format = this._format; + let format = this._format$; let ext = ''; const SupportTextureFormats = macro.SUPPORT_TEXTURE_FORMATS; for (const extensionID of extensionIDs) { @@ -748,7 +749,7 @@ export class ImageAsset extends Asset { const index = SupportTextureFormats.indexOf(tmpExt); if (index !== -1 && index < preferedExtensionIndex) { - const fmt = extFormat[1] ? parseInt(extFormat[1]) : this._format; + const fmt = extFormat[1] ? parseInt(extFormat[1]) : this._format$; // check whether or not support compressed texture if (tmpExt === '.astc' && (!device || !(device.getFormatFeatures(Format.ASTC_RGBA_4X4) & FormatFeatureBit.SAMPLED_TEXTURE))) { continue; @@ -771,26 +772,26 @@ export class ImageAsset extends Asset { if (ext) { this._setRawAsset(ext); - this._format = format; + this._format$ = format; } else { warnID(3121); } } - private static _sharedPlaceHolderCanvas: HTMLCanvasElement | null = null; + private static _sharedPlaceHolderCanvas$: HTMLCanvasElement | null = null; public initDefault (uuid?: string): void { super.initDefault(uuid); - if (!ImageAsset._sharedPlaceHolderCanvas) { + if (!ImageAsset._sharedPlaceHolderCanvas$) { const canvas = ccwindow.document.createElement('canvas'); const context = canvas.getContext('2d')!; const l = canvas.width = canvas.height = 2; context.fillStyle = '#ff00ff'; context.fillRect(0, 0, l, l); this.reset(canvas); - ImageAsset._sharedPlaceHolderCanvas = canvas; + ImageAsset._sharedPlaceHolderCanvas$ = canvas; } else { - this.reset(ImageAsset._sharedPlaceHolderCanvas); + this.reset(ImageAsset._sharedPlaceHolderCanvas$); } } diff --git a/cocos/asset/assets/render-texture.ts b/cocos/asset/assets/render-texture.ts index c1e3dc42004..57bbf736f9f 100644 --- a/cocos/asset/assets/render-texture.ts +++ b/cocos/asset/assets/render-texture.ts @@ -60,7 +60,7 @@ const _windowInfo: IRenderWindowInfo = { */ @ccclass('cc.RenderTexture') export class RenderTexture extends TextureBase { - private _window: RenderWindow | null = null; + private _window$: RenderWindow | null = null; constructor () { super(); } @@ -70,7 +70,7 @@ export class RenderTexture extends TextureBase { * @zh 渲染管线所使用的渲染窗口,内部逻辑创建,无法被修改。 */ get window (): RenderWindow | null { - return this._window; + return this._window$; } /** @@ -99,10 +99,10 @@ export class RenderTexture extends TextureBase { * @zh 销毁渲染贴图。 */ public destroy (): boolean { - if (this._window) { + if (this._window$) { const root = cclegacy.director.root as Root; - root?.destroyWindow(this._window); - this._window = null; + root?.destroyWindow(this._window$); + this._window$ = null; } return super.destroy(); @@ -117,10 +117,10 @@ export class RenderTexture extends TextureBase { public resize (width: number, height: number): void { this._width = Math.floor(clamp(width, 1, 2048)); this._height = Math.floor(clamp(height, 1, 2048)); - if (this._window) { - this._window.resize(this._width, this._height); + if (this._window$) { + this._window$.resize(this._width, this._height); } - this.emit('resize', this._window); + this.emit('resize', this._window$); } /** @@ -151,7 +151,7 @@ export class RenderTexture extends TextureBase { * @return @en The low level gfx texture. @zh 底层的 gfx 贴图。 */ public getGFXTexture (): Texture | null { - return this._window && this._window.framebuffer.colorTextures[0]; + return this._window$ && this._window$.framebuffer.colorTextures[0]; } /** @@ -187,11 +187,11 @@ export class RenderTexture extends TextureBase { AccessFlagBit.FRAGMENT_SHADER_READ_TEXTURE, )); - if (this._window) { - this._window.destroy(); - this._window.initialize(deviceManager.gfxDevice, _windowInfo); + if (this._window$) { + this._window$.destroy(); + this._window$.initialize(deviceManager.gfxDevice, _windowInfo); } else { - this._window = root.createWindow(_windowInfo); + this._window$ = root.createWindow(_windowInfo); } } diff --git a/cocos/asset/assets/rendering-sub-mesh.ts b/cocos/asset/assets/rendering-sub-mesh.ts index ea9c4eee21f..5657d237bd3 100644 --- a/cocos/asset/assets/rendering-sub-mesh.ts +++ b/cocos/asset/assets/rendering-sub-mesh.ts @@ -77,6 +77,12 @@ export interface IFlatBuffer { buffer: Uint8Array; } +const EMPTY_GEOMETRIC_INFO: IGeometricInfo = { + positions: new Float32Array(), + indices: new Uint8Array(), + boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO }, +}; + /** * @en Sub mesh for rendering which contains all geometry data, it can be used to create [[gfx.InputAssembler]]. * @zh 包含所有顶点数据的渲染子网格,可以用来创建 [[gfx.InputAssembler]]。 @@ -98,37 +104,31 @@ export class RenderingSubMesh { */ public subMeshIdx?: number; - private _flatBuffers: IFlatBuffer[] = []; - - private _jointMappedBuffers?: Buffer[]; + private _flatBuffers$: IFlatBuffer[] = []; - private _jointMappedBufferIndices?: number[]; + private _jointMappedBuffers$?: Buffer[]; - private _vertexIdChannel?: { stream: number; index: number }; + private _jointMappedBufferIndices$?: number[]; - private _geometricInfo?: IGeometricInfo; + private _vertexIdChannel$?: { stream: number; index: number }; - private _vertexBuffers: Buffer[]; + private _geometricInfo$?: IGeometricInfo; - private declare _attributes: Attribute[]; + private _vertexBuffers$: Buffer[]; - private declare _indexBuffer: Buffer | null; + private declare _attributes$: Attribute[]; - private declare _indirectBuffer: Buffer | null; + private declare _indexBuffer$: Buffer | null; - private declare _primitiveMode: PrimitiveMode; + private declare _indirectBuffer$: Buffer | null; - private declare _iaInfo: InputAssemblerInfo; + private declare _primitiveMode$: PrimitiveMode; - private declare _isOwnerOfIndexBuffer: boolean; + private declare _iaInfo$: InputAssemblerInfo; - private _drawInfo?: DrawInfo | null = null; + private declare _isOwnerOfIndexBuffer$: boolean; - private static EMPTY_GEOMETRIC_INFO: IGeometricInfo = { - positions: new Float32Array(), - indices: new Uint8Array(), - boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO }, - }; + private _drawInfo$?: DrawInfo | null = null; /** * @en @@ -149,64 +149,64 @@ export class RenderingSubMesh { indirectBuffer: Buffer | null = null, isOwnerOfIndexBuffer = true, ) { - this._attributes = attributes; - this._vertexBuffers = vertexBuffers; - this._indexBuffer = indexBuffer; - this._indirectBuffer = indirectBuffer; - this._primitiveMode = primitiveMode; - this._iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer); - this._isOwnerOfIndexBuffer = isOwnerOfIndexBuffer; + this._attributes$ = attributes; + this._vertexBuffers$ = vertexBuffers; + this._indexBuffer$ = indexBuffer; + this._indirectBuffer$ = indirectBuffer; + this._primitiveMode$ = primitiveMode; + this._iaInfo$ = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer); + this._isOwnerOfIndexBuffer$ = isOwnerOfIndexBuffer; } /** * @en All vertex attributes used by the sub mesh. * @zh 所有顶点属性。 */ - get attributes (): Attribute[] { return this._attributes; } + get attributes (): Attribute[] { return this._attributes$; } /** * @en All vertex buffers used by the sub mesh. * @zh 使用的所有顶点缓冲区。 */ - get vertexBuffers (): Buffer[] { return this._vertexBuffers; } + get vertexBuffers (): Buffer[] { return this._vertexBuffers$; } /** * @en Index buffer used by the sub mesh. * @zh 使用的索引缓冲区,若未使用则无需指定。 */ - get indexBuffer (): Buffer | null { return this._indexBuffer; } + get indexBuffer (): Buffer | null { return this._indexBuffer$; } /** * @en Indirect buffer used by the sub mesh. * @zh 间接绘制缓冲区。 */ - get indirectBuffer (): Buffer | null { return this._indirectBuffer; } + get indirectBuffer (): Buffer | null { return this._indirectBuffer$; } /** * @en Primitive mode used by the sub mesh. * @zh 图元类型。 */ - get primitiveMode (): PrimitiveMode { return this._primitiveMode; } + get primitiveMode (): PrimitiveMode { return this._primitiveMode$; } /** * @en The geometric info of the sub mesh, used for raycast. * @zh (用于射线检测的)几何信息。 */ get geometricInfo (): IGeometricInfo { - if (this._geometricInfo) { - return this._geometricInfo; + if (this._geometricInfo$) { + return this._geometricInfo$; } if (this.mesh === undefined) { - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } if (this.subMeshIdx === undefined) { - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } const { mesh } = this; const index = this.subMeshIdx; const pAttri = this.attributes.find((element) => element.name === (AttributeName.ATTR_POSITION as string)); if (!pAttri) { - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } let positions: Float32Array | undefined; @@ -216,7 +216,7 @@ export class RenderingSubMesh { { positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array; if (!positions) { - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } break; } @@ -224,7 +224,7 @@ export class RenderingSubMesh { { const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array; if (!data) { - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } const count = data.length / 4; positions = new Float32Array(count * 3); @@ -242,7 +242,7 @@ export class RenderingSubMesh { { const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Uint16Array; if (!data) { - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } positions = new Float32Array(data.length); for (let i = 0; i < data.length; ++i) { @@ -254,7 +254,7 @@ export class RenderingSubMesh { { const data = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Uint16Array; if (!data) { - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } const count = data.length / 4; positions = new Float32Array(count * 3); @@ -268,7 +268,7 @@ export class RenderingSubMesh { break; } default: - return RenderingSubMesh.EMPTY_GEOMETRIC_INFO; + return EMPTY_GEOMETRIC_INFO; } const indices = mesh.readIndices(index) || undefined; @@ -298,40 +298,40 @@ export class RenderingSubMesh { min.z = positions[i + 2] < min.z ? positions[i + 2] : min.z; } } - this._geometricInfo = { positions, indices, boundingBox: { max, min } }; - return this._geometricInfo; + this._geometricInfo$ = { positions, indices, boundingBox: { max, min } }; + return this._geometricInfo$; } /** * @en Invalidate the geometric info of the sub mesh after geometry changed. * @zh 网格更新后,设置(用于射线检测的)几何信息为无效,需要重新计算。 */ - public invalidateGeometricInfo (): void { this._geometricInfo = undefined; } + public invalidateGeometricInfo (): void { this._geometricInfo$ = undefined; } /** * @en the draw range. * @zh 渲染范围。 */ set drawInfo (info: DrawInfo | null | undefined) { - this._drawInfo = info; + this._drawInfo$ = info; } get drawInfo (): DrawInfo | null | undefined { - return this._drawInfo; + return this._drawInfo$; } /** * @en Flatted vertex buffers. * @zh 扁平化的顶点缓冲区。 */ - get flatBuffers (): IFlatBuffer[] { return this._flatBuffers; } + get flatBuffers (): IFlatBuffer[] { return this._flatBuffers$; } /** * @en generate flatted vertex buffers. * @zh 生成扁平化的顶点缓冲区。 */ public genFlatBuffers (): void { - if (this._flatBuffers.length || !this.mesh || this.subMeshIdx === undefined) { return; } + if (this._flatBuffers$.length || !this.mesh || this.subMeshIdx === undefined) { return; } const { mesh } = this; let idxCount = 0; @@ -348,7 +348,7 @@ export class RenderingSubMesh { if (!prim.indexView) { sharedView.set(mesh.data.subarray(vertexBundle.view.offset, vertexBundle.view.offset + vertexBundle.view.length)); - this._flatBuffers.push({ stride: vbStride, count: vbCount, buffer: sharedView }); + this._flatBuffers$.push({ stride: vbStride, count: vbCount, buffer: sharedView }); continue; } @@ -362,7 +362,7 @@ export class RenderingSubMesh { sharedView[offset + m] = view[srcOffset + m]; } } - this._flatBuffers.push({ stride: vbStride, count: vbCount, buffer: sharedView }); + this._flatBuffers$.push({ stride: vbStride, count: vbCount, buffer: sharedView }); } } @@ -371,14 +371,14 @@ export class RenderingSubMesh { * @zh 骨骼索引按映射表处理后的顶点缓冲。 */ get jointMappedBuffers (): Buffer[] { - if (this._jointMappedBuffers) { return this._jointMappedBuffers; } - const buffers: Buffer[] = this._jointMappedBuffers = []; - const indices: number[] = this._jointMappedBufferIndices = []; - if (!this.mesh || this.subMeshIdx === undefined) { return this._jointMappedBuffers = this.vertexBuffers; } + if (this._jointMappedBuffers$) { return this._jointMappedBuffers$; } + const buffers: Buffer[] = this._jointMappedBuffers$ = []; + const indices: number[] = this._jointMappedBufferIndices$ = []; + if (!this.mesh || this.subMeshIdx === undefined) { return this._jointMappedBuffers$ = this.vertexBuffers; } const { struct } = this.mesh; const prim = struct.primitives[this.subMeshIdx]; if (!struct.jointMaps || prim.jointMapIndex === undefined || !struct.jointMaps[prim.jointMapIndex]) { - return this._jointMappedBuffers = this.vertexBuffers; + return this._jointMappedBuffers$ = this.vertexBuffers; } let jointFormat: Format; let jointOffset: number; @@ -419,7 +419,7 @@ export class RenderingSubMesh { buffers.push(this.vertexBuffers[prim.vertexBundelIndices[i]]); } } - if (this._vertexIdChannel) { + if (this._vertexIdChannel$) { buffers.push(this._allocVertexIdBuffer(device)); } return buffers; @@ -429,7 +429,7 @@ export class RenderingSubMesh { * @en The input assembler info. * @zh 输入汇集器信息。 */ - get iaInfo (): InputAssemblerInfo { return this._iaInfo; } + get iaInfo (): InputAssemblerInfo { return this._iaInfo$; } /** * @en Destroys sub mesh. @@ -440,22 +440,22 @@ export class RenderingSubMesh { this.vertexBuffers[i].destroy(); } this.vertexBuffers.length = 0; - if (this._indexBuffer) { - if (this._isOwnerOfIndexBuffer) { - this._indexBuffer.destroy(); + if (this._indexBuffer$) { + if (this._isOwnerOfIndexBuffer$) { + this._indexBuffer$.destroy(); } - this._indexBuffer = null; + this._indexBuffer$ = null; } - if (this._jointMappedBuffers && this._jointMappedBufferIndices) { - for (let i = 0; i < this._jointMappedBufferIndices.length; i++) { - this._jointMappedBuffers[this._jointMappedBufferIndices[i]].destroy(); + if (this._jointMappedBuffers$ && this._jointMappedBufferIndices$) { + for (let i = 0; i < this._jointMappedBufferIndices$.length; i++) { + this._jointMappedBuffers$[this._jointMappedBufferIndices$[i]].destroy(); } - this._jointMappedBuffers = undefined; - this._jointMappedBufferIndices = undefined; + this._jointMappedBuffers$ = undefined; + this._jointMappedBufferIndices$ = undefined; } - if (this._indirectBuffer) { - this._indirectBuffer.destroy(); - this._indirectBuffer = null; + if (this._indirectBuffer$) { + this._indirectBuffer$.destroy(); + this._indirectBuffer$ = null; } } @@ -469,7 +469,7 @@ export class RenderingSubMesh { * @param device @en Device used to create related rendering resources @zh 用于创建相关渲染资源的设备对象 */ public enableVertexIdChannel (device: Device): void { - if (this._vertexIdChannel) { + if (this._vertexIdChannel$) { return; } @@ -477,13 +477,13 @@ export class RenderingSubMesh { const attributeIndex = this.attributes.length; const vertexIdBuffer = this._allocVertexIdBuffer(device); - this._vertexBuffers.push(vertexIdBuffer); - this._attributes.push(new Attribute('a_vertexId', Format.R32F, false, streamIndex)); + this._vertexBuffers$.push(vertexIdBuffer); + this._attributes$.push(new Attribute('a_vertexId', Format.R32F, false, streamIndex)); - this._iaInfo.attributes = this._attributes; - this._iaInfo.vertexBuffers = this._vertexBuffers; + this._iaInfo$.attributes = this._attributes$; + this._iaInfo$.vertexBuffers = this._vertexBuffers$; - this._vertexIdChannel = { + this._vertexIdChannel$ = { stream: streamIndex, index: attributeIndex, }; diff --git a/cocos/asset/assets/simple-texture.ts b/cocos/asset/assets/simple-texture.ts index 434e0731568..2d099dc9511 100644 --- a/cocos/asset/assets/simple-texture.ts +++ b/cocos/asset/assets/simple-texture.ts @@ -67,10 +67,10 @@ export class SimpleTexture extends TextureBase { * @engineInternal */ protected _gfxTextureView: Texture | null = null; - private _mipmapLevel = 1; + private _mipmapLevel$ = 1; // Cache these data to reduce JSB invoking. - private _textureWidth = 0; - private _textureHeight = 0; + private _textureWidth$ = 0; + private _textureHeight$ = 0; /** * @engineInternal @@ -90,7 +90,7 @@ export class SimpleTexture extends TextureBase { * @zh 贴图中的 Mipmap 层级数量。 */ get mipmapLevel (): number { - return this._mipmapLevel; + return this._mipmapLevel$; } /** @@ -145,7 +145,7 @@ export class SimpleTexture extends TextureBase { * @param arrayIndex @en The array index. @zh 要上传的数组索引。 */ public uploadData (source: HTMLCanvasElement | HTMLImageElement | ArrayBufferView | ImageBitmap, level = 0, arrayIndex = 0): void { - if (!this._gfxTexture || this._mipmapLevel <= level) { + if (!this._gfxTexture || this._mipmapLevel$ <= level) { return; } @@ -155,8 +155,8 @@ export class SimpleTexture extends TextureBase { } const region = _regions[0]; - region.texExtent.width = this._textureWidth >> level; - region.texExtent.height = this._textureHeight >> level; + region.texExtent.width = this._textureWidth$ >> level; + region.texExtent.height = this._textureHeight$ >> level; region.texSubres.mipLevel = level; region.texSubres.baseArrayLayer = arrayIndex; @@ -223,7 +223,7 @@ export class SimpleTexture extends TextureBase { * */ protected _setMipmapLevel (value: number): void { - this._mipmapLevel = value < 1 ? 1 : value; + this._mipmapLevel$ = value < 1 ? 1 : value; } /** @@ -282,7 +282,7 @@ export class SimpleTexture extends TextureBase { protected _tryReset (): void { this._tryDestroyTextureView(); this._tryDestroyTexture(); - if (this._mipmapLevel === 0) { + if (this._mipmapLevel$ === 0) { return; } const device = this._getGFXDevice(); @@ -308,7 +308,7 @@ export class SimpleTexture extends TextureBase { if (this._width === 0 || this._height === 0) { return; } let flags = TextureFlagBit.NONE; if (this._mipFilter !== Filter.NONE && canGenerateMipmap(device, this._width, this._height)) { - this._mipmapLevel = getMipLevel(this._width, this._height); + this._mipmapLevel$ = getMipLevel(this._width, this._height); if (!this.isUsingOfflineMipmaps() && !this.isCompressed) { flags = TextureFlagBit.GEN_MIPMAP; } @@ -316,7 +316,7 @@ export class SimpleTexture extends TextureBase { const textureCreateInfo = this._getGfxTextureCreateInfo({ usage: TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST | TextureUsageBit.COLOR_ATTACHMENT, format: this._getGFXFormat(), - levelCount: this._mipmapLevel, + levelCount: this._mipmapLevel$, flags, }); if (!textureCreateInfo) { @@ -324,8 +324,8 @@ export class SimpleTexture extends TextureBase { } const texture = device.createTexture(textureCreateInfo); - this._textureWidth = textureCreateInfo.width; - this._textureHeight = textureCreateInfo.height; + this._textureWidth$ = textureCreateInfo.width; + this._textureHeight$ = textureCreateInfo.height; this._gfxTexture = texture; } @@ -337,7 +337,7 @@ export class SimpleTexture extends TextureBase { if (!this._gfxTexture) { return null; } - const maxLevel = this._maxLevel < this._mipmapLevel ? this._maxLevel : this._mipmapLevel - 1; + const maxLevel = this._maxLevel < this._mipmapLevel$ ? this._maxLevel : this._mipmapLevel$ - 1; const textureViewCreateInfo = this._getGfxTextureViewCreateInfo({ texture: this._gfxTexture, format: this._getGFXFormat(), diff --git a/cocos/asset/assets/texture-2d.ts b/cocos/asset/assets/texture-2d.ts index 6454b04a599..a5cc835ede5 100644 --- a/cocos/asset/assets/texture-2d.ts +++ b/cocos/asset/assets/texture-2d.ts @@ -112,26 +112,26 @@ export class Texture2D extends SimpleTexture { } } - this._setMipmapParams(mipmaps); + this._setMipmapParams$(mipmaps); } /** * TODO: See: cocos/cocos-engine#15305 */ - private _setMipmapParams (value: ImageAsset[]): void { - this._generatedMipmaps = value; - this._setMipmapLevel(this._generatedMipmaps.length); - if (this._generatedMipmaps.length > 0) { - const imageAsset: ImageAsset = this._generatedMipmaps[0]; + private _setMipmapParams$ (value: ImageAsset[]): void { + this._generatedMipmaps$ = value; + this._setMipmapLevel(this._generatedMipmaps$.length); + if (this._generatedMipmaps$.length > 0) { + const imageAsset: ImageAsset = this._generatedMipmaps$[0]; this.reset({ width: imageAsset.width, height: imageAsset.height, format: imageAsset.format, - mipmapLevel: this._generatedMipmaps.length, + mipmapLevel: this._generatedMipmaps$.length, baseLevel: this._baseLevel, maxLevel: this._maxLevel, }); - this._generatedMipmaps.forEach((mipmap, level) => { + this._generatedMipmaps$.forEach((mipmap, level) => { this._assignImage(mipmap, level); }); // @@ -139,7 +139,7 @@ export class Texture2D extends SimpleTexture { this.reset({ width: 0, height: 0, - mipmapLevel: this._generatedMipmaps.length, + mipmapLevel: this._generatedMipmaps$.length, baseLevel: this._baseLevel, maxLevel: this._maxLevel, }); @@ -168,7 +168,7 @@ export class Texture2D extends SimpleTexture { @type([ImageAsset]) public _mipmaps: ImageAsset[] = []; - private _generatedMipmaps: ImageAsset[] = []; + private _generatedMipmaps$: ImageAsset[] = []; /** * @engineInternal @@ -229,18 +229,18 @@ export class Texture2D extends SimpleTexture { } public updateMipmaps (firstLevel = 0, count: number | undefined = undefined): void { - if (firstLevel >= this._generatedMipmaps.length) { + if (firstLevel >= this._generatedMipmaps$.length) { return; } const nUpdate = Math.min( - count === undefined ? this._generatedMipmaps.length : count, - this._generatedMipmaps.length - firstLevel, + count === undefined ? this._generatedMipmaps$.length : count, + this._generatedMipmaps$.length - firstLevel, ); for (let i = 0; i < nUpdate; ++i) { const level = firstLevel + i; - this._assignImage(this._generatedMipmaps[level], level); + this._assignImage(this._generatedMipmaps$[level], level); } } @@ -260,7 +260,7 @@ export class Texture2D extends SimpleTexture { */ public destroy (): boolean { this._mipmaps = []; - this._generatedMipmaps = []; + this._generatedMipmaps$ = []; return super.destroy(); } diff --git a/cocos/asset/assets/texture-base.ts b/cocos/asset/assets/texture-base.ts index 81a00d8e3c1..77f7aa36753 100644 --- a/cocos/asset/assets/texture-base.ts +++ b/cocos/asset/assets/texture-base.ts @@ -140,19 +140,19 @@ export class TextureBase extends Asset { protected _height = 1; private declare _id: string; - private _samplerInfo = new SamplerInfo(); - private _gfxSampler: Sampler | null = null; - private _gfxDevice: Device | null = null; + private _samplerInfo$ = new SamplerInfo(); + private _gfxSampler$: Sampler | null = null; + private _gfxDevice$: Device | null = null; - private _textureHash = 0; + private _textureHash$ = 0; constructor () { super(); // Id for generate hash in material this._id = idGenerator.getNewId(); - this._gfxDevice = this._getGFXDevice(); - this._textureHash = murmurhash2_32_gc(this._id, 666); + this._gfxDevice$ = this._getGFXDevice(); + this._textureHash$ = murmurhash2_32_gc(this._id, 666); } /** @@ -195,14 +195,14 @@ export class TextureBase extends Asset { if (wrapR === undefined) wrapR = wrapS; // wrap modes should be as consistent as possible for performance this._wrapS = wrapS; - this._samplerInfo.addressU = wrapS as unknown as Address; + this._samplerInfo$.addressU = wrapS as unknown as Address; this._wrapT = wrapT; - this._samplerInfo.addressV = wrapT as unknown as Address; + this._samplerInfo$.addressV = wrapT as unknown as Address; this._wrapR = wrapR; - this._samplerInfo.addressW = wrapR as unknown as Address; + this._samplerInfo$.addressW = wrapR as unknown as Address; - if (this._gfxDevice) { - this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo); + if (this._gfxDevice$) { + this._gfxSampler$ = this._gfxDevice$.getSampler(this._samplerInfo$); } } @@ -214,12 +214,12 @@ export class TextureBase extends Asset { */ public setFilters (minFilter: Filter, magFilter: Filter): void { this._minFilter = minFilter; - this._samplerInfo.minFilter = minFilter as unknown as GFXFilter; + this._samplerInfo$.minFilter = minFilter as unknown as GFXFilter; this._magFilter = magFilter; - this._samplerInfo.magFilter = magFilter as unknown as GFXFilter; + this._samplerInfo$.magFilter = magFilter as unknown as GFXFilter; - if (this._gfxDevice) { - this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo); + if (this._gfxDevice$) { + this._gfxSampler$ = this._gfxDevice$.getSampler(this._samplerInfo$); } } @@ -230,10 +230,10 @@ export class TextureBase extends Asset { */ public setMipFilter (mipFilter: Filter): void { this._mipFilter = mipFilter; - this._samplerInfo.mipFilter = mipFilter as unknown as GFXFilter; + this._samplerInfo$.mipFilter = mipFilter as unknown as GFXFilter; - if (this._gfxDevice) { - this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo); + if (this._gfxDevice$) { + this._gfxSampler$ = this._gfxDevice$.getSampler(this._samplerInfo$); } } @@ -244,10 +244,10 @@ export class TextureBase extends Asset { */ public setAnisotropy (anisotropy: number): void { this._anisotropy = anisotropy; - this._samplerInfo.maxAnisotropy = anisotropy; + this._samplerInfo$.maxAnisotropy = anisotropy; - if (this._gfxDevice) { - this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo); + if (this._gfxDevice$) { + this._gfxSampler$ = this._gfxDevice$.getSampler(this._samplerInfo$); } } @@ -258,7 +258,7 @@ export class TextureBase extends Asset { public destroy (): boolean { const destroyed = super.destroy(); if (destroyed && cclegacy.director.root?.batcher2D) { - cclegacy.director.root.batcher2D._releaseDescriptorSetCache(this._textureHash); + cclegacy.director.root.batcher2D._releaseDescriptorSetCache(this._textureHash$); } return destroyed; } @@ -268,7 +268,7 @@ export class TextureBase extends Asset { * @zh 获取此贴图的哈希值。 */ public getHash (): number { - return this._textureHash; + return this._textureHash$; } /** @@ -285,7 +285,7 @@ export class TextureBase extends Asset { * @private */ public getSamplerInfo (): Readonly { - return this._samplerInfo; + return this._samplerInfo$; } /** @@ -293,14 +293,14 @@ export class TextureBase extends Asset { * @zh 获取此贴图底层的 GFX 采样信息。 */ public getGFXSampler (): Sampler { - if (!this._gfxSampler) { - if (this._gfxDevice) { - this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo); + if (!this._gfxSampler$) { + if (this._gfxDevice$) { + this._gfxSampler$ = this._gfxDevice$.getSampler(this._samplerInfo$); } else { errorID(9302); } } - return this._gfxSampler!; + return this._gfxSampler$!; } // SERIALIZATION diff --git a/cocos/asset/assets/texture-cube.ts b/cocos/asset/assets/texture-cube.ts index c7db6870a7f..734446cfd36 100644 --- a/cocos/asset/assets/texture-cube.ts +++ b/cocos/asset/assets/texture-cube.ts @@ -161,7 +161,7 @@ export class TextureCube extends SimpleTexture { || front.length !== top.length || front.length !== bottom.length) { errorID(16347); - this._setMipmapParams([]); + this._setMipmapParams$([]); return; } @@ -191,23 +191,23 @@ export class TextureCube extends SimpleTexture { }); } - this._setMipmapParams(cubeMaps); + this._setMipmapParams$(cubeMaps); } - private _setMipmapParams (value: ITextureCubeMipmap[]): void { - this._generatedMipmaps = value; - this._setMipmapLevel(this._generatedMipmaps.length); - if (this._generatedMipmaps.length > 0) { - const imageAsset: ImageAsset = this._generatedMipmaps[0].front; + private _setMipmapParams$ (value: ITextureCubeMipmap[]): void { + this._generatedMipmaps$ = value; + this._setMipmapLevel(this._generatedMipmaps$.length); + if (this._generatedMipmaps$.length > 0) { + const imageAsset: ImageAsset = this._generatedMipmaps$[0].front; this.reset({ width: imageAsset.width, height: imageAsset.height, format: imageAsset.format, - mipmapLevel: this._generatedMipmaps.length, + mipmapLevel: this._generatedMipmaps$.length, baseLevel: this._baseLevel, maxLevel: this._maxLevel, }); - this._generatedMipmaps.forEach((mipmap, level): void => { + this._generatedMipmaps$.forEach((mipmap, level): void => { _forEachFace(mipmap, (face, faceIndex): void => { this._assignImage(face, level, faceIndex); }); @@ -216,7 +216,7 @@ export class TextureCube extends SimpleTexture { this.reset({ width: 0, height: 0, - mipmapLevel: this._generatedMipmaps.length, + mipmapLevel: this._generatedMipmaps$.length, baseLevel: this._baseLevel, maxLevel: this._maxLevel, }); @@ -359,7 +359,7 @@ export class TextureCube extends SimpleTexture { @serializable public _mipmaps: ITextureCubeMipmap[] = []; - private _generatedMipmaps: ITextureCubeMipmap[] = []; + private _generatedMipmaps$: ITextureCubeMipmap[] = []; public onLoaded (): void { if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { @@ -396,18 +396,18 @@ export class TextureCube extends SimpleTexture { * @param count @en Mipmap level count to be updated。 @zh 指定要更新层的数量。 */ public updateMipmaps (firstLevel = 0, count: number | undefined = undefined): void { - if (firstLevel >= this._generatedMipmaps.length) { + if (firstLevel >= this._generatedMipmaps$.length) { return; } const nUpdate = Math.min( - count === undefined ? this._generatedMipmaps.length : count, - this._generatedMipmaps.length - firstLevel, + count === undefined ? this._generatedMipmaps$.length : count, + this._generatedMipmaps$.length - firstLevel, ); for (let i = 0; i < nUpdate; ++i) { const level = firstLevel + i; - _forEachFace(this._generatedMipmaps[level], (face, faceIndex): void => { + _forEachFace(this._generatedMipmaps$[level], (face, faceIndex): void => { this._assignImage(face, level, faceIndex); }); } @@ -419,7 +419,7 @@ export class TextureCube extends SimpleTexture { */ public destroy (): boolean { this._mipmaps = []; - this._generatedMipmaps = []; + this._generatedMipmaps$ = []; this._mipmapAtlas = null; return super.destroy(); } diff --git a/cocos/core/curves/quat-curve.ts b/cocos/core/curves/quat-curve.ts index e6bca7c3233..704f7607258 100644 --- a/cocos/core/curves/quat-curve.ts +++ b/cocos/core/curves/quat-curve.ts @@ -343,7 +343,7 @@ export class QuatCurve extends KeyframeCurve { // Flags let flags = 0; - if (interpolationModeRepeated) { flags |= KeyframeValueFlagMask.INTERPOLATION_MODE; } + if (interpolationModeRepeated) { flags |= QuatCurveKeyframeValueFlagMask.INTERPOLATION_MODE; } dataView.setUint32(P, flags, true); P += FLAGS_BYTES; // Frame count @@ -408,7 +408,7 @@ export class QuatCurve extends KeyframeCurve { // Flags const flags = dataView.getUint32(P, true); P += FLAGS_BYTES; - const interpolationModeRepeated = flags & KeyframeValueFlagMask.INTERPOLATION_MODE; + const interpolationModeRepeated = flags & QuatCurveKeyframeValueFlagMask.INTERPOLATION_MODE; // Frame count const nFrames = dataView.getUint32(P, true); P += FRAME_COUNT_BYTES; @@ -469,7 +469,7 @@ export class QuatCurve extends KeyframeCurve { } } -enum KeyframeValueFlagMask { +enum QuatCurveKeyframeValueFlagMask { INTERPOLATION_MODE = 1 << 0, } diff --git a/cocos/core/data/garbage-collection.ts b/cocos/core/data/garbage-collection.ts index d2de7650448..0b0e7c798a5 100644 --- a/cocos/core/data/garbage-collection.ts +++ b/cocos/core/data/garbage-collection.ts @@ -20,7 +20,7 @@ THE SOFTWARE. */ import { EDITOR } from 'internal:constants'; -import { GCObject } from './gc-object'; +import type { GCObject } from './gc-object'; declare class FinalizationRegistry { constructor (callback: (heldObj: any) => void); @@ -31,11 +31,11 @@ declare class FinalizationRegistry { const targetSymbol = Symbol('[[target]]'); class GarbageCollectionManager { - private _finalizationRegistry: FinalizationRegistry | null = EDITOR && typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry(this.finalizationRegistryCallback.bind(this)) : null; - private _gcObjects: WeakMap = new WeakMap(); + private _finalizationRegistry$: FinalizationRegistry | null = EDITOR && typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry(this.finalizationRegistryCallback$.bind(this)) : null; + private _gcObjects$: WeakMap = new WeakMap(); public registerGCObject (gcObject: GCObject): GCObject { - if (EDITOR && this._finalizationRegistry) { + if (EDITOR && this._finalizationRegistry$) { const token = {}; const proxy = new Proxy(gcObject, { get (target, property, receiver): unknown { @@ -57,8 +57,8 @@ class GarbageCollectionManager { return true; }, }); - this._gcObjects.set(token, gcObject); - this._finalizationRegistry.register(proxy, token, token); + this._gcObjects$.set(token, gcObject); + this._finalizationRegistry$.register(proxy, token, token); return proxy; } else { return gcObject; @@ -68,13 +68,13 @@ class GarbageCollectionManager { public init (): void { } - private finalizationRegistryCallback (token: any): void { - const gcObject = this._gcObjects.get(token); + private finalizationRegistryCallback$ (token: any): void { + const gcObject = this._gcObjects$.get(token); if (gcObject) { - this._gcObjects.delete(token); + this._gcObjects$.delete(token); gcObject.destroy(); } - this._finalizationRegistry!.unregister(token); + this._finalizationRegistry$!.unregister(token); } public destroy (): void { diff --git a/cocos/core/data/gc-object.ts b/cocos/core/data/gc-object.ts index 845cf662a43..08952e74aff 100644 --- a/cocos/core/data/gc-object.ts +++ b/cocos/core/data/gc-object.ts @@ -26,6 +26,7 @@ import { garbageCollectionManager } from './garbage-collection'; */ export class GCObject { constructor () { + // eslint-disable-next-line no-constructor-return return garbageCollectionManager.registerGCObject(this); } diff --git a/cocos/core/event/async-delegate.ts b/cocos/core/event/async-delegate.ts index f1d31bd1567..dd0445b960b 100644 --- a/cocos/core/event/async-delegate.ts +++ b/cocos/core/event/async-delegate.ts @@ -47,7 +47,7 @@ import { array } from '../utils/js'; * ``` */ export class AsyncDelegate (Promise | void) = () => (Promise | void)> { - private _delegates: T[] = []; + private _delegates$: T[] = []; /** * @en @@ -61,8 +61,8 @@ export class AsyncDelegate (Promise | void) = * @zh 要添加的回调,并将在该委托调度时被调用。 */ public add (callback: T): void { - if (!this._delegates.includes(callback)) { - this._delegates.push(callback); + if (!this._delegates$.includes(callback)) { + this._delegates$.push(callback); } } @@ -76,7 +76,7 @@ export class AsyncDelegate (Promise | void) = * @returns @en Whether the callback has been added. @zh 是否已经添加了回调。 */ public hasListener (callback: T): boolean { - return this._delegates.includes(callback); + return this._delegates$.includes(callback); } /** @@ -89,7 +89,7 @@ export class AsyncDelegate (Promise | void) = * @param callback @en The callback to remove. @zh 要移除的某个回调。 */ public remove (callback: T): void { - array.fastRemove(this._delegates, callback); + array.fastRemove(this._delegates$, callback); } /** @@ -103,6 +103,6 @@ export class AsyncDelegate (Promise | void) = * @returns @en The promise awaiting all async callback resolved. @zh 等待所有异步回调结束的 Promise 对象。 */ public dispatch (...args: Parameters): Promise { - return Promise.all(this._delegates.map((func) => func(...arguments)).filter(Boolean)); + return Promise.all(this._delegates$.map((func) => func(...arguments)).filter(Boolean)); } } diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index a5f137f734c..7a46e931b14 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -184,7 +184,7 @@ export class CallbacksInvoker { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _callbackTable: ICallbackTable = createMap(true); - private _offCallback?: () => void; + private _offCallback$?: () => void; /** * @zh 向一个事件名注册一个新的事件监听器,包含回调函数和调用者 @@ -307,7 +307,7 @@ export class CallbacksInvoker { this.removeAll(key); } } - this._offCallback?.(); + this._offCallback$?.(); } /** @@ -375,7 +375,7 @@ export class CallbacksInvoker { * @engineInternal */ public _registerOffCallback (cb: () => void): void { - this._offCallback = cb; + this._offCallback$ = cb; } } diff --git a/cocos/core/geometry/aabb.ts b/cocos/core/geometry/aabb.ts index ccfcb64b0ac..0bf5641cea1 100644 --- a/cocos/core/geometry/aabb.ts +++ b/cocos/core/geometry/aabb.ts @@ -24,7 +24,7 @@ import { DEBUG } from 'internal:constants'; import { Mat3, Mat4, Quat, Vec3 } from '../math'; -import enums from './enums'; +import { ShapeType } from './enums'; import { IVec3, IVec3Like } from '../math/type-define'; import { Sphere } from './sphere'; import { Frustum } from './frustum'; @@ -239,7 +239,7 @@ export class AABB { protected readonly _type: number; constructor (px = 0, py = 0, pz = 0, hw = 1, hh = 1, hl = 1) { - this._type = enums.SHAPE_AABB; + this._type = ShapeType.SHAPE_AABB; this.center = new Vec3(px, py, pz); this.halfExtents = new Vec3(hw, hh, hl); diff --git a/cocos/core/geometry/capsule.ts b/cocos/core/geometry/capsule.ts index a40028ef946..8fc1779c59f 100644 --- a/cocos/core/geometry/capsule.ts +++ b/cocos/core/geometry/capsule.ts @@ -23,7 +23,7 @@ */ import { Vec3, Quat, Mat4, absMaxComponent } from '../math'; -import enums from './enums'; +import { ShapeType } from './enums'; import { IVec3Like, IQuatLike } from '../math/type-define'; /** @@ -35,9 +35,9 @@ import { IVec3Like, IQuatLike } from '../math/type-define'; export class Capsule { /** * @en - * Gets the type of this Capsule, always returns `enums.SHAPE_CAPSULE`. + * Gets the type of this Capsule, always returns `ShapeType.SHAPE_CAPSULE`. * @zh - * 获取此形状的类型,值固定为 `enums.SHAPE_CAPSULE`。 + * 获取此形状的类型,值固定为 `ShapeType.SHAPE_CAPSULE`。 */ get type (): number { return this._type; @@ -105,7 +105,7 @@ export class Capsule { * @param axis @en The local orientation of this capsule [0,1,2] => [x,y,z]. @zh 胶囊体的本地朝向,映射关系 [0,1,2] => [x,y,z]。 */ constructor (radius = 0.5, halfHeight = 0.5, axis = 1) { - this._type = enums.SHAPE_CAPSULE; + this._type = ShapeType.SHAPE_CAPSULE; this.radius = radius; this.halfHeight = halfHeight; this.axis = axis; diff --git a/cocos/core/geometry/curve.ts b/cocos/core/geometry/curve.ts index 9580e510722..519e9036dda 100644 --- a/cocos/core/geometry/curve.ts +++ b/cocos/core/geometry/curve.ts @@ -271,7 +271,7 @@ export class AnimationCurve { if (wrappedTime >= cachedKey.time && wrappedTime < cachedKey.endTime) { return cachedKey.evaluate(wrappedTime); } - const leftIndex = this.findIndex(cachedKey, wrappedTime); + const leftIndex = this.findIndex$(cachedKey, wrappedTime); const rightIndex = Math.min(leftIndex + 1, lastKeyframeIndex); this.calcOptimizedKey(cachedKey, leftIndex, rightIndex); return cachedKey.evaluate(wrappedTime); @@ -309,7 +309,7 @@ export class AnimationCurve { * @param optKey * @param t */ - private findIndex (optKey: OptimizedKey, t: number): number { + private findIndex$ (optKey: OptimizedKey, t: number): number { const { _curve: curve } = this; const nKeyframes = curve.keyFramesCount; const cachedIndex = optKey.index; diff --git a/cocos/core/geometry/enums.ts b/cocos/core/geometry/enums.ts index 2bf8a7fd925..7e7bc857a22 100644 --- a/cocos/core/geometry/enums.ts +++ b/cocos/core/geometry/enums.ts @@ -33,16 +33,18 @@ * @zh * 形状的类型值。 */ -export default { - SHAPE_RAY: (1 << 0), - SHAPE_LINE: (1 << 1), - SHAPE_SPHERE: (1 << 2), - SHAPE_AABB: (1 << 3), - SHAPE_OBB: (1 << 4), - SHAPE_PLANE: (1 << 5), - SHAPE_TRIANGLE: (1 << 6), - SHAPE_FRUSTUM: (1 << 7), - SHAPE_FRUSTUM_ACCURATE: (1 << 8), - SHAPE_CAPSULE: (1 << 9), - SHAPE_SPLINE: (1 << 10), -}; +export enum ShapeType { + SHAPE_RAY = (1 << 0), + SHAPE_LINE = (1 << 1), + SHAPE_SPHERE = (1 << 2), + SHAPE_AABB = (1 << 3), + SHAPE_OBB = (1 << 4), + SHAPE_PLANE = (1 << 5), + SHAPE_TRIANGLE = (1 << 6), + SHAPE_FRUSTUM = (1 << 7), + SHAPE_FRUSTUM_ACCURATE = (1 << 8), + SHAPE_CAPSULE = (1 << 9), + SHAPE_SPLINE = (1 << 10), +} + +export default ShapeType; diff --git a/cocos/core/geometry/frustum.ts b/cocos/core/geometry/frustum.ts index 72d6a27eba9..c7efc606dd1 100644 --- a/cocos/core/geometry/frustum.ts +++ b/cocos/core/geometry/frustum.ts @@ -22,24 +22,24 @@ THE SOFTWARE. */ -import { Mat4, Vec3 } from '../math'; -import enums from './enums'; +import { Mat4, v3, Vec3 } from '../math'; +import { ShapeType } from './enums'; import { Plane } from './plane'; import { AABB } from './aabb'; -const _v = new Array(8); -_v[0] = new Vec3(1, 1, 1); -_v[1] = new Vec3(-1, 1, 1); -_v[2] = new Vec3(-1, -1, 1); -_v[3] = new Vec3(1, -1, 1); -_v[4] = new Vec3(1, 1, -1); -_v[5] = new Vec3(-1, 1, -1); -_v[6] = new Vec3(-1, -1, -1); -_v[7] = new Vec3(1, -1, -1); +const _v = new Array(8); +_v[0] = v3(1, 1, 1); +_v[1] = v3(-1, 1, 1); +_v[2] = v3(-1, -1, 1); +_v[3] = v3(1, -1, 1); +_v[4] = v3(1, 1, -1); +_v[5] = v3(-1, 1, -1); +_v[6] = v3(-1, -1, -1); +_v[7] = v3(1, -1, -1); -const _nearTemp = new Vec3(); -const _farTemp = new Vec3(); -const _temp_v3 = new Vec3(); +const _nearTemp = v3(); +const _farTemp = v3(); +const _temp_v3 = v3(); /** * @en @@ -234,14 +234,14 @@ export class Frustum { * @deprecated since v3.8.0 no need to set accurate flag since it doesn't affect the calculation at all. */ set accurate (b: boolean) { - this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; + this._type = b ? ShapeType.SHAPE_FRUSTUM_ACCURATE : ShapeType.SHAPE_FRUSTUM; } /** * @en - * Gets the type of the shape. The value may be `enums.SHAPE_FRUSTUM_ACCURATE` or `enums.SHAPE_FRUSTUM`. + * Gets the type of the shape. The value may be `ShapeType.SHAPE_FRUSTUM_ACCURATE` or `ShapeType.SHAPE_FRUSTUM`. * @zh - * 获取形状的类型。值可能为 `enums.SHAPE_FRUSTUM_ACCURATE` 或 `enums.SHAPE_FRUSTUM`。 + * 获取形状的类型。值可能为 `ShapeType.SHAPE_FRUSTUM_ACCURATE` 或 `ShapeType.SHAPE_FRUSTUM`。 * @readonly */ get type (): number { @@ -267,7 +267,7 @@ export class Frustum { protected _type: number; constructor () { - this._type = enums.SHAPE_FRUSTUM; + this._type = ShapeType.SHAPE_FRUSTUM; this.planes = new Array(6); for (let i = 0; i < 6; ++i) { this.planes[i] = Plane.create(0, 0, 0, 0); diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index fff0a2702dc..f428ca84a6f 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -26,7 +26,7 @@ import { EPSILON, Mat3, Vec3 } from '../math'; import { AABB } from './aabb'; import { Capsule } from './capsule'; import * as distance from './distance'; -import enums from './enums'; +import { ShapeType } from './enums'; import { Frustum } from './frustum'; import { Line } from './line'; import { OBB } from './obb'; @@ -579,8 +579,9 @@ function getOBBVertices (c: Vec3, e: Vec3, a1: Vec3, a2: Vec3, a3: Vec3, out: Ve ); } -function getInterval (vertices: any[] | Vec3[], axis: Vec3): number[] { - let min = Vec3.dot(axis, vertices[0]); let max = min; +function getInterval (vertices: IVec3Like[], axis: Vec3): number[] { + let min = Vec3.dot(axis, vertices[0]); + let max = min; for (let i = 1; i < 8; ++i) { const projection = Vec3.dot(axis, vertices[i]); min = (projection < min) ? projection : min; @@ -599,12 +600,12 @@ function getInterval (vertices: any[] | Vec3[], axis: Vec3): number[] { * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ const aabbWithOBB = (function (): (aabb: AABB, obb: OBB) => number { - const test = new Array(15); + const test = new Array(15); for (let i = 0; i < 15; i++) { test[i] = new Vec3(0, 0, 0); } - const vertices = new Array(8); - const vertices2 = new Array(8); + const vertices = new Array(8); + const vertices2 = new Array(8); for (let i = 0; i < 8; i++) { vertices[i] = new Vec3(0, 0, 0); vertices2[i] = new Vec3(0, 0, 0); @@ -822,7 +823,7 @@ const obbFrustum = function (obb: OBB, frustum: Frustum): number { * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ const obbFrustumAccurate = (function (): (obb: OBB, frustum: Frustum) => number { - const tmp = new Array(8); + const tmp = new Array(8); let dist = 0; let out1 = 0; let out2 = 0; for (let i = 0; i < tmp.length; i++) { tmp[i] = new Vec3(0, 0, 0); @@ -877,13 +878,13 @@ const obbFrustumAccurate = (function (): (obb: OBB, frustum: Frustum) => number * @returns @zh 如果没有相交,返回 0 ,否则返回非 0。 @en zero if no intersection, otherwise returns a non-zero value.no intersection */ const obbWithOBB = (function (): (obb1: OBB, obb2: OBB) => number { - const test = new Array(15); + const test = new Array(15); for (let i = 0; i < 15; i++) { test[i] = new Vec3(0, 0, 0); } - const vertices = new Array(8); - const vertices2 = new Array(8); + const vertices = new Array(8); + const vertices2 = new Array(8); for (let i = 0; i < 8; i++) { vertices[i] = new Vec3(0, 0, 0); vertices2[i] = new Vec3(0, 0, 0); @@ -1290,39 +1291,39 @@ const intersect = { }, }; -intersect[enums.SHAPE_RAY | enums.SHAPE_SPHERE] = raySphere; -intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = rayAABB; -intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = rayOBB; -intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = rayPlane; -intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = rayTriangle; -intersect[enums.SHAPE_RAY | enums.SHAPE_CAPSULE] = rayCapsule; - -intersect[enums.SHAPE_LINE | enums.SHAPE_SPHERE] = lineSphere; -intersect[enums.SHAPE_LINE | enums.SHAPE_AABB] = lineAABB; -intersect[enums.SHAPE_LINE | enums.SHAPE_OBB] = lineOBB; -intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = linePlane; -intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = lineTriangle; - -intersect[enums.SHAPE_SPHERE] = sphereWithSphere; -intersect[enums.SHAPE_SPHERE | enums.SHAPE_AABB] = sphereAABB; -intersect[enums.SHAPE_SPHERE | enums.SHAPE_OBB] = sphereOBB; -intersect[enums.SHAPE_SPHERE | enums.SHAPE_PLANE] = spherePlane; -intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM] = sphereFrustum; -intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM_ACCURATE] = sphereFrustumAccurate; -intersect[enums.SHAPE_SPHERE | enums.SHAPE_CAPSULE] = sphereCapsule; - -intersect[enums.SHAPE_AABB] = aabbWithAABB; -intersect[enums.SHAPE_AABB | enums.SHAPE_OBB] = aabbWithOBB; -intersect[enums.SHAPE_AABB | enums.SHAPE_PLANE] = aabbPlane; -intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM] = aabbFrustum; -intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM_ACCURATE] = aabbFrustumAccurate; - -intersect[enums.SHAPE_OBB] = obbWithOBB; -intersect[enums.SHAPE_OBB | enums.SHAPE_PLANE] = obbPlane; -intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM] = obbFrustum; -intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM_ACCURATE] = obbFrustumAccurate; -intersect[enums.SHAPE_OBB | enums.SHAPE_CAPSULE] = obbCapsule; - -intersect[enums.SHAPE_CAPSULE] = capsuleWithCapsule; +intersect[ShapeType.SHAPE_RAY | ShapeType.SHAPE_SPHERE] = raySphere; +intersect[ShapeType.SHAPE_RAY | ShapeType.SHAPE_AABB] = rayAABB; +intersect[ShapeType.SHAPE_RAY | ShapeType.SHAPE_OBB] = rayOBB; +intersect[ShapeType.SHAPE_RAY | ShapeType.SHAPE_PLANE] = rayPlane; +intersect[ShapeType.SHAPE_RAY | ShapeType.SHAPE_TRIANGLE] = rayTriangle; +intersect[ShapeType.SHAPE_RAY | ShapeType.SHAPE_CAPSULE] = rayCapsule; + +intersect[ShapeType.SHAPE_LINE | ShapeType.SHAPE_SPHERE] = lineSphere; +intersect[ShapeType.SHAPE_LINE | ShapeType.SHAPE_AABB] = lineAABB; +intersect[ShapeType.SHAPE_LINE | ShapeType.SHAPE_OBB] = lineOBB; +intersect[ShapeType.SHAPE_LINE | ShapeType.SHAPE_PLANE] = linePlane; +intersect[ShapeType.SHAPE_LINE | ShapeType.SHAPE_TRIANGLE] = lineTriangle; + +intersect[ShapeType.SHAPE_SPHERE] = sphereWithSphere; +intersect[ShapeType.SHAPE_SPHERE | ShapeType.SHAPE_AABB] = sphereAABB; +intersect[ShapeType.SHAPE_SPHERE | ShapeType.SHAPE_OBB] = sphereOBB; +intersect[ShapeType.SHAPE_SPHERE | ShapeType.SHAPE_PLANE] = spherePlane; +intersect[ShapeType.SHAPE_SPHERE | ShapeType.SHAPE_FRUSTUM] = sphereFrustum; +intersect[ShapeType.SHAPE_SPHERE | ShapeType.SHAPE_FRUSTUM_ACCURATE] = sphereFrustumAccurate; +intersect[ShapeType.SHAPE_SPHERE | ShapeType.SHAPE_CAPSULE] = sphereCapsule; + +intersect[ShapeType.SHAPE_AABB] = aabbWithAABB; +intersect[ShapeType.SHAPE_AABB | ShapeType.SHAPE_OBB] = aabbWithOBB; +intersect[ShapeType.SHAPE_AABB | ShapeType.SHAPE_PLANE] = aabbPlane; +intersect[ShapeType.SHAPE_AABB | ShapeType.SHAPE_FRUSTUM] = aabbFrustum; +intersect[ShapeType.SHAPE_AABB | ShapeType.SHAPE_FRUSTUM_ACCURATE] = aabbFrustumAccurate; + +intersect[ShapeType.SHAPE_OBB] = obbWithOBB; +intersect[ShapeType.SHAPE_OBB | ShapeType.SHAPE_PLANE] = obbPlane; +intersect[ShapeType.SHAPE_OBB | ShapeType.SHAPE_FRUSTUM] = obbFrustum; +intersect[ShapeType.SHAPE_OBB | ShapeType.SHAPE_FRUSTUM_ACCURATE] = obbFrustumAccurate; +intersect[ShapeType.SHAPE_OBB | ShapeType.SHAPE_CAPSULE] = obbCapsule; + +intersect[ShapeType.SHAPE_CAPSULE] = capsuleWithCapsule; export default intersect; diff --git a/cocos/core/geometry/line.ts b/cocos/core/geometry/line.ts index 7e2f1b0c1c7..b17b48e727e 100644 --- a/cocos/core/geometry/line.ts +++ b/cocos/core/geometry/line.ts @@ -23,7 +23,7 @@ */ import { Vec3 } from '../math'; -import enums from './enums'; +import { ShapeType } from './enums'; /** * @en @@ -59,8 +59,12 @@ export class Line { */ public static clone (a: Line): Line { return new Line( - a.s.x, a.s.y, a.s.z, - a.e.x, a.e.y, a.e.z, + a.s.x, + a.s.y, + a.s.z, + a.e.x, + a.e.y, + a.e.z, ); } @@ -144,8 +148,8 @@ export class Line { public e: Vec3; /** - * @en Gets the type of the shape. Always returns `enums.SHAPE_LINE`. - * @zh 获取形状的类型,总是返回 `enums.SHAPE_LINE`。 + * @en Gets the type of the shape. Always returns `ShapeType.SHAPE_LINE`. + * @zh 获取形状的类型,总是返回 `ShapeType.SHAPE_LINE`。 */ get type (): number { return this._type; @@ -164,7 +168,7 @@ export class Line { * @param ez @en the z coordinate of the end position. @zh 终点的 z 坐标。 */ constructor (sx = 0, sy = 0, sz = 0, ex = 0, ey = 0, ez = -1) { - this._type = enums.SHAPE_LINE; + this._type = ShapeType.SHAPE_LINE; this.s = new Vec3(sx, sy, sz); this.e = new Vec3(ex, ey, ez); } diff --git a/cocos/core/geometry/obb.ts b/cocos/core/geometry/obb.ts index a450042d88d..177fa9c69da 100644 --- a/cocos/core/geometry/obb.ts +++ b/cocos/core/geometry/obb.ts @@ -23,7 +23,7 @@ */ import { Mat3, Mat4, Quat, Vec3 } from '../math'; -import enums from './enums'; +import { ShapeType } from './enums'; const _v3_tmp = new Vec3(); const _v3_tmp2 = new Vec3(); @@ -68,11 +68,21 @@ export class OBB { * @returns @zh 返回新创建的 OBB 实例。 @en A new OBB instance. */ public static create ( - cx: number, cy: number, cz: number, - hw: number, hh: number, hl: number, - ox_1: number, ox_2: number, ox_3: number, - oy_1: number, oy_2: number, oy_3: number, - oz_1: number, oz_2: number, oz_3: number, + cx: number, + cy: number, + cz: number, + hw: number, + hh: number, + hl: number, + ox_1: number, + ox_2: number, + ox_3: number, + oy_1: number, + oy_2: number, + oy_3: number, + oz_1: number, + oz_2: number, + oz_3: number, ): OBB { return new OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); } @@ -86,11 +96,23 @@ export class OBB { * @returns @zh The cloned OBB instance. @en 克隆出的新对象。 */ public static clone (a: OBB): OBB { - return new OBB(a.center.x, a.center.y, a.center.z, - a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, - a.orientation.m00, a.orientation.m01, a.orientation.m02, - a.orientation.m03, a.orientation.m04, a.orientation.m05, - a.orientation.m06, a.orientation.m07, a.orientation.m08); + return new OBB( + a.center.x, + a.center.y, + a.center.z, + a.halfExtents.x, + a.halfExtents.y, + a.halfExtents.z, + a.orientation.m00, + a.orientation.m01, + a.orientation.m02, + a.orientation.m03, + a.orientation.m04, + a.orientation.m05, + a.orientation.m06, + a.orientation.m07, + a.orientation.m08, + ); } /** @@ -152,11 +174,21 @@ export class OBB { */ public static set ( out: OBB, - cx: number, cy: number, cz: number, - hw: number, hh: number, hl: number, - ox_1: number, ox_2: number, ox_3: number, - oy_1: number, oy_2: number, oy_3: number, - oz_1: number, oz_2: number, oz_3: number, + cx: number, + cy: number, + cz: number, + hw: number, + hh: number, + hl: number, + ox_1: number, + ox_2: number, + ox_3: number, + oy_1: number, + oy_2: number, + oy_3: number, + oz_1: number, + oz_2: number, + oz_3: number, ): OBB { Vec3.set(out.center, cx, cy, cz); Vec3.set(out.halfExtents, hw, hh, hl); @@ -190,9 +222,9 @@ export class OBB { /** * @en - * Gets the type of the OBB. Always returns `enums.SHAPE_OBB`. + * Gets the type of the OBB. Always returns `ShapeType.SHAPE_OBB`. * @zh - * 获取形状的类型,固定返回 `enums.SHAPE_OBB`。 + * 获取形状的类型,固定返回 `ShapeType.SHAPE_OBB`。 */ get type (): number { return this._type; @@ -217,12 +249,24 @@ export class OBB { * @param oz_2 @zh 方向矩阵参数,第 2 条轴的 z 分量。 @en The z component of the second axis of the OBB. * @param oz_3 @zh 方向矩阵参数,第 3 条轴的 z 分量。 @en The z component of the third axis of the OBB. */ - constructor (cx = 0, cy = 0, cz = 0, - hw = 1, hh = 1, hl = 1, - ox_1 = 1, ox_2 = 0, ox_3 = 0, - oy_1 = 0, oy_2 = 1, oy_3 = 0, - oz_1 = 0, oz_2 = 0, oz_3 = 1) { - this._type = enums.SHAPE_OBB; + constructor ( + cx = 0, + cy = 0, + cz = 0, + hw = 1, + hh = 1, + hl = 1, + ox_1 = 1, + ox_2 = 0, + ox_3 = 0, + oy_1 = 0, + oy_2 = 1, + oy_3 = 0, + oz_1 = 0, + oz_2 = 0, + oz_3 = 1, + ) { + this._type = ShapeType.SHAPE_OBB; this.center = new Vec3(cx, cy, cz); this.halfExtents = new Vec3(hw, hh, hl); this.orientation = new Mat3(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3); diff --git a/cocos/core/geometry/plane.ts b/cocos/core/geometry/plane.ts index d4242388adf..749a973b1e3 100644 --- a/cocos/core/geometry/plane.ts +++ b/cocos/core/geometry/plane.ts @@ -22,14 +22,13 @@ THE SOFTWARE. */ -import { Mat4, Vec3, Vec4 } from '../math'; -import enums from './enums'; -import { legacyCC } from '../global-exports'; +import { mat4, Mat4, v4, Vec3, Vec4 } from '../math'; +import { ShapeType } from './enums'; const v1 = new Vec3(0, 0, 0); const v2 = new Vec3(0, 0, 0); -const temp_mat = legacyCC.mat4(); -const temp_vec4 = legacyCC.v4(); +const temp_mat = mat4(); +const temp_vec4 = v4(); /** * @en @@ -179,9 +178,9 @@ export class Plane { /** * @en - * Gets the type of the Plane, its value is `enums.SHAPE_PLANE`. + * Gets the type of the Plane, its value is `ShapeType.SHAPE_PLANE`. * @zh - * 获取形状的类型,值为 `enums.SHAPE_PLANE`。 + * 获取形状的类型,值为 `ShapeType.SHAPE_PLANE`。 */ get type (): number { return this._type; @@ -210,7 +209,7 @@ export class Plane { * @param d @en The distance between normal vector and the origin. @zh 与原点的距离。 */ constructor (nx = 0, ny = 1, nz = 0, d = 0) { - this._type = enums.SHAPE_PLANE; + this._type = ShapeType.SHAPE_PLANE; this.n = new Vec3(nx, ny, nz); this.d = d; } diff --git a/cocos/core/geometry/ray.ts b/cocos/core/geometry/ray.ts index 530979b6432..b8fed887e2e 100644 --- a/cocos/core/geometry/ray.ts +++ b/cocos/core/geometry/ray.ts @@ -23,7 +23,7 @@ */ import { Vec3 } from '../math'; -import enums from './enums'; +import { ShapeType } from './enums'; import { IVec3Like } from '../math/type-define'; /** @@ -145,15 +145,15 @@ export class Ray { /** * @en - * Gets the type of the ray, its value is `enums.SHAPE_RAY`. + * Gets the type of the ray, its value is `ShapeType.SHAPE_RAY`. * @zh - * 获取形状的类型,其值为`enums.SHAPE_RAY`。 + * 获取形状的类型,其值为`ShapeType.SHAPE_RAY`。 */ get type (): number { return this._type; } - protected readonly _type: number = enums.SHAPE_RAY; + protected readonly _type: number = ShapeType.SHAPE_RAY; /** * @en diff --git a/cocos/core/geometry/sphere.ts b/cocos/core/geometry/sphere.ts index 7fdce2da628..77415d422e8 100644 --- a/cocos/core/geometry/sphere.ts +++ b/cocos/core/geometry/sphere.ts @@ -23,7 +23,7 @@ */ import { Mat4, Quat, Vec3 } from '../math'; -import enums from './enums'; +import { ShapeType } from './enums'; import { AABB } from './aabb'; const _v3_tmp = new Vec3(); @@ -154,15 +154,15 @@ export class Sphere { /** * @en - * Gets the type of the shape, always returns `enums.SHAPE_SPHERE`. + * Gets the type of the shape, always returns `ShapeType.SHAPE_SPHERE`. * @zh - * 获取球的类型,固定返回 `enums.SHAPE_SPHERE`。 + * 获取球的类型,固定返回 `ShapeType.SHAPE_SPHERE`。 */ get type (): number { return this._type; } - protected readonly _type: number = enums.SHAPE_SPHERE; + protected readonly _type: number = ShapeType.SHAPE_SPHERE; /** * @en diff --git a/cocos/core/geometry/spline.ts b/cocos/core/geometry/spline.ts index 876d4a0141c..95ea49fbba2 100644 --- a/cocos/core/geometry/spline.ts +++ b/cocos/core/geometry/spline.ts @@ -25,7 +25,7 @@ import { assertIsTrue } from '../data/utils/asserts'; import { clamp, Vec3 } from '../math'; import { warnID } from '../platform/debug'; -import enums from './enums'; +import { ShapeType } from './enums'; export enum SplineMode { /** @@ -89,16 +89,16 @@ const _v3 = new Vec3(); */ export class Spline { - private readonly _type: number; - private _mode: SplineMode = SplineMode.CATMULL_ROM; - private _knots: Vec3[] = []; + private readonly _type$: number; + private _mode$: SplineMode = SplineMode.CATMULL_ROM; + private _knots$: Vec3[] = []; private constructor (mode: SplineMode = SplineMode.CATMULL_ROM, knots: Readonly = []) { - this._type = enums.SHAPE_SPLINE; - this._mode = mode; + this._type$ = ShapeType.SHAPE_SPLINE; + this._mode$ = mode; for (let i = 0; i < knots.length; i++) { - this._knots[i] = new Vec3(knots[i]); + this._knots$[i] = new Vec3(knots[i]); } } @@ -137,13 +137,13 @@ export class Spline { * @returns @en The target Spline instance to copy to, same as the `out` parameter. @zh 拷贝目标 Spline 实例,值与 `out` 参数相同。 */ public static copy (out: Spline, s: Spline): Spline { - out._mode = s.mode; - out._knots.length = 0; + out._mode$ = s.mode; + out._knots$.length = 0; const knots = s.knots; const length = knots.length; for (let i = 0; i < length; i++) { - out._knots[i] = new Vec3(knots[i]); + out._knots$[i] = new Vec3(knots[i]); } return out; @@ -151,12 +151,12 @@ export class Spline { /** * @en - * Gets the type of this Spline instance, always returns `enums.SHAPE_SPLINE`. + * Gets the type of this Spline instance, always returns `ShapeType.SHAPE_SPLINE`. * @zh - * 获取此 Spline 的类型,固定返回 `enums.SHAPE_SPLINE` + * 获取此 Spline 的类型,固定返回 `ShapeType.SHAPE_SPLINE` */ get type (): number { - return this._type; + return this._type$; } /** @@ -166,7 +166,7 @@ export class Spline { * 获取当前 Spline 实例的模式。 */ get mode (): SplineMode { - return this._mode; + return this._mode$; } /** @@ -176,7 +176,7 @@ export class Spline { * 获取当前 Spline 实例的所有结点。 */ get knots (): Readonly { - return this._knots; + return this._knots$; } /** @@ -188,11 +188,11 @@ export class Spline { * @param knots @en The knots to be set to this spline instance. @zh 要设置到当前 Spline 实例的结点列表。 */ public setModeAndKnots (mode: SplineMode, knots: Vec3[]): void { - this._mode = mode; - this._knots.length = 0; + this._mode$ = mode; + this._knots$.length = 0; for (let i = 0; i < knots.length; i++) { - this._knots[i] = new Vec3(knots[i]); + this._knots$[i] = new Vec3(knots[i]); } } @@ -203,7 +203,7 @@ export class Spline { * 清空当前 Spline 实例的所有结点。 */ public clearKnots (): void { - this._knots.length = 0; + this._knots$.length = 0; } /** @@ -214,7 +214,7 @@ export class Spline { * @returns @en The knot count of this Spline instance. @zh 当前 Spline 实例的结点数量。 */ public getKnotCount (): number { - return this._knots.length; + return this._knots$.length; } /** @@ -225,7 +225,7 @@ export class Spline { * @param knot @en The knot to add to this Spline instance. @zh 要添加到当前 Spline 实例的结点。 */ public addKnot (knot: Vec3): void { - this._knots.push(new Vec3(knot)); + this._knots$.push(new Vec3(knot)); } /** @@ -238,12 +238,12 @@ export class Spline { */ public insertKnot (index: number, knot: Vec3): void { const item = new Vec3(knot); - if (index >= this._knots.length) { - this._knots.push(item); + if (index >= this._knots$.length) { + this._knots$.push(item); return; } - this._knots.splice(index, 0, item); + this._knots$.splice(index, 0, item); } /** @@ -254,9 +254,9 @@ export class Spline { * @param index */ public removeKnot (index: number): void { - assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); + assertIsTrue(index >= 0 && index < this._knots$.length, 'Spline: invalid index'); - this._knots.splice(index, 1); + this._knots$.splice(index, 1); } /** @@ -268,9 +268,9 @@ export class Spline { * @param knot @en The knot to be set to the specified position. @zh 要设置的结点。 */ public setKnot (index: number, knot: Vec3): void { - assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); + assertIsTrue(index >= 0 && index < this._knots$.length, 'Spline: invalid index'); - this._knots[index].set(knot); + this._knots$[index].set(knot); } /** @@ -282,9 +282,9 @@ export class Spline { * @returns @en The knot of the specified position of this Spline instance. @zh 当前 Spline 实例指定位置的结点。 */ public getKnot (index: number): Readonly { - assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); + assertIsTrue(index >= 0 && index < this._knots$.length, 'Spline: invalid index'); - return this._knots[index]; + return this._knots$[index]; } /** @@ -312,18 +312,18 @@ export class Spline { } if (index >= segments) { - return new Vec3(this._knots[this._knots.length - 1]); + return new Vec3(this._knots$[this._knots$.length - 1]); } - switch (this._mode) { + switch (this._mode$) { case SplineMode.LINEAR: - return Spline.calcLinear(this._knots[index], this._knots[index + 1], t); + return Spline.calcLinear$(this._knots$[index], this._knots$[index + 1], t); case SplineMode.BEZIER: - return Spline.calcBezier(this._knots[index * 4], this._knots[index * 4 + 1], this._knots[index * 4 + 2], this._knots[index * 4 + 3], t); + return Spline.calcBezier$(this._knots$[index * 4], this._knots$[index * 4 + 1], this._knots$[index * 4 + 2], this._knots$[index * 4 + 3], t); case SplineMode.CATMULL_ROM: { - const v0 = index > 0 ? this._knots[index - 1] : this._knots[index]; - const v3 = index + 2 < this._knots.length ? this._knots[index + 2] : this._knots[index + 1]; - return Spline.calcCatmullRom(v0, this._knots[index], this._knots[index + 1], v3, t); + const v0 = index > 0 ? this._knots$[index - 1] : this._knots$[index]; + const v3 = index + 2 < this._knots$.length ? this._knots$[index + 2] : this._knots$[index + 1]; + return Spline.calcCatmullRom$(v0, this._knots$[index], this._knots$[index + 1], v3, t); } default: return new Vec3(0.0, 0.0, 0.0); @@ -362,9 +362,10 @@ export class Spline { return points; } + // eslint-disable-next-line consistent-return private getSegments (): number { - const count = this._knots.length; - switch (this._mode) { + const count = this._knots$.length; + switch (this._mode$) { case SplineMode.LINEAR: case SplineMode.CATMULL_ROM: if (count < 2) { @@ -374,7 +375,7 @@ export class Spline { return count - 1; case SplineMode.BEZIER: - if (count < 4 || count % 4 != 0) { + if (count < 4 || count % 4 !== 0) { warnID(14301); return 0; } @@ -385,7 +386,7 @@ export class Spline { } } - private static calcLinear (v0: Vec3, v1: Vec3, t: number): Vec3 { + private static calcLinear$ (v0: Vec3, v1: Vec3, t: number): Vec3 { const result = new Vec3(); Vec3.multiplyScalar(_v0, v0, (1.0 - t)); Vec3.multiplyScalar(_v1, v1, t); @@ -394,7 +395,7 @@ export class Spline { return result; } - private static calcBezier (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number): Vec3 { + private static calcBezier$ (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number): Vec3 { const result = new Vec3(); const s = 1.0 - t; Vec3.multiplyScalar(_v0, v0, s * s * s); @@ -407,7 +408,7 @@ export class Spline { return result; } - private static calcCatmullRom (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number): Vec3 { + private static calcCatmullRom$ (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number): Vec3 { const result = new Vec3(); const t2 = t * t; const t3 = t2 * t; diff --git a/cocos/core/geometry/triangle.ts b/cocos/core/geometry/triangle.ts index 568bcb44143..dce8d84f594 100644 --- a/cocos/core/geometry/triangle.ts +++ b/cocos/core/geometry/triangle.ts @@ -23,7 +23,7 @@ */ import { Vec3 } from '../math'; -import enums from './enums'; +import { ShapeType } from './enums'; /** * @en @@ -190,15 +190,15 @@ export class Triangle { /** * @en - * Gets the type of the triangle, always returns `enums.SHAPE_TRIANGLE`. + * Gets the type of the triangle, always returns `ShapeType.SHAPE_TRIANGLE`. * @zh - * 获取此三角形的类型,固定返回 `enums.SHAPE_TRIANGLE`。 + * 获取此三角形的类型,固定返回 `ShapeType.SHAPE_TRIANGLE`。 */ get type (): number { return this._type; } - protected readonly _type: number = enums.SHAPE_TRIANGLE; + protected readonly _type: number = ShapeType.SHAPE_TRIANGLE; /** * @en diff --git a/cocos/core/math/affine-transform.ts b/cocos/core/math/affine-transform.ts index 00b86bf96fa..6718acbeb38 100644 --- a/cocos/core/math/affine-transform.ts +++ b/cocos/core/math/affine-transform.ts @@ -51,9 +51,12 @@ export class AffineTransform { */ public static clone (affineTransform: AffineTransform): AffineTransform { return new AffineTransform( - affineTransform.a, affineTransform.b, - affineTransform.c, affineTransform.d, - affineTransform.tx, affineTransform.ty, + affineTransform.a, + affineTransform.b, + affineTransform.c, + affineTransform.d, + affineTransform.tx, + affineTransform.ty, ); } @@ -118,7 +121,7 @@ export class AffineTransform { * @param point Vector to apply transform. * @param t transform matrix. */ - public static transformVec2 (out: Vec2, point: Vec2, t: AffineTransform): any; + public static transformVec2 (out: Vec2, point: Vec2, t: AffineTransform): void; /** * @en Apply the `AffineTransform` on a 2D vector. @@ -128,9 +131,9 @@ export class AffineTransform { * @param y y to apply transform. * @param t transform matrix. */ - public static transformVec2 (out: Vec2, x: number, y: number, t: AffineTransform): any; + public static transformVec2 (out: Vec2, x: number, y: number, t: AffineTransform): void; - public static transformVec2 (out: Vec2, point: Vec2 | number, transOrY: AffineTransform | number, t?: AffineTransform): any { + public static transformVec2 (out: Vec2, point: Vec2 | number, transOrY: AffineTransform | number, t?: AffineTransform): void { let x: number; let y: number; if (!t) { @@ -199,8 +202,15 @@ export class AffineTransform { * @param rect The rect object to apply transform. * @param anAffineTransform transform matrix. */ - public static transformObb (out_bl: Vec2, out_tl: Vec2, out_tr: Vec2, out_br: Vec2, rect: Rect, - anAffineTransform: AffineTransform, flipY = true): void { + public static transformObb ( + out_bl: Vec2, + out_tl: Vec2, + out_tr: Vec2, + out_br: Vec2, + rect: Rect, + anAffineTransform: AffineTransform, + flipY = true, + ): void { const tx = anAffineTransform.a * rect.x + anAffineTransform.c * rect.y + anAffineTransform.tx; const ty = anAffineTransform.b * rect.x + anAffineTransform.d * rect.y + anAffineTransform.ty; const xa = anAffineTransform.a * rect.width; diff --git a/cocos/core/math/mat3.ts b/cocos/core/math/mat3.ts index 38e48bb7068..6c5101129a4 100644 --- a/cocos/core/math/mat3.ts +++ b/cocos/core/math/mat3.ts @@ -33,6 +33,9 @@ import { EPSILON, HALF_PI } from './utils'; import { Vec3 } from './vec3'; import { legacyCC } from '../global-exports'; +const abs = Math.abs; +const max = Math.max; + /** * @en Mathematical 3x3 matrix. * @zh 表示三维(3x3)矩阵。 @@ -151,9 +154,7 @@ export class Mat3 extends ValueType { let det = a00 * b01 + a01 * b11 + a02 * b21; if (det === 0) { - out.m00 = 0; out.m01 = 0; out.m02 = 0; - out.m03 = 0; out.m04 = 0; out.m05 = 0; - out.m06 = 0; out.m07 = 0; out.m08 = 0; + Mat3.set(out, 0, 0, 0, 0, 0, 0, 0, 0, 0); return out; } det = 1.0 / det; @@ -628,15 +629,15 @@ export class Mat3 extends ValueType { */ public static equals (a: Out, b: Out, epsilon = EPSILON): boolean { return ( - Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) - && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) - && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) - && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) - && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) - && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) - && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) - && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) - && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08)) + abs(a.m00 - b.m00) <= epsilon * max(1.0, abs(a.m00), abs(b.m00)) + && abs(a.m01 - b.m01) <= epsilon * max(1.0, abs(a.m01), abs(b.m01)) + && abs(a.m02 - b.m02) <= epsilon * max(1.0, abs(a.m02), abs(b.m02)) + && abs(a.m03 - b.m03) <= epsilon * max(1.0, abs(a.m03), abs(b.m03)) + && abs(a.m04 - b.m04) <= epsilon * max(1.0, abs(a.m04), abs(b.m04)) + && abs(a.m05 - b.m05) <= epsilon * max(1.0, abs(a.m05), abs(b.m05)) + && abs(a.m06 - b.m06) <= epsilon * max(1.0, abs(a.m06), abs(b.m06)) + && abs(a.m07 - b.m07) <= epsilon * max(1.0, abs(a.m07), abs(b.m07)) + && abs(a.m08 - b.m08) <= epsilon * max(1.0, abs(a.m08), abs(b.m08)) ); } @@ -749,14 +750,15 @@ export class Mat3 extends ValueType { m06 = 0, m07 = 0, m08 = 1, ) { super(); + const self = this; if (typeof m00 === 'object') { - this.m00 = m00.m00; this.m01 = m00.m01; this.m02 = m00.m02; - this.m03 = m00.m03; this.m04 = m00.m04; this.m05 = m00.m05; - this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; + self.m00 = m00.m00; self.m01 = m00.m01; self.m02 = m00.m02; + self.m03 = m00.m03; self.m04 = m00.m04; self.m05 = m00.m05; + self.m06 = m00.m06; self.m07 = m00.m07; self.m08 = m00.m08; } else { - this.m00 = m00; this.m01 = m01; this.m02 = m02; - this.m03 = m03; this.m04 = m04; this.m05 = m05; - this.m06 = m06; this.m07 = m07; this.m08 = m08; + self.m00 = m00; self.m01 = m01; self.m02 = m02; + self.m03 = m03; self.m04 = m04; self.m05 = m05; + self.m06 = m06; self.m07 = m07; self.m08 = m08; } } @@ -765,12 +767,7 @@ export class Mat3 extends ValueType { * @zh 克隆当前矩阵。 */ public clone (): Mat3 { - const t = this; - return new Mat3( - t.m00, t.m01, t.m02, - t.m03, t.m04, t.m05, - t.m06, t.m07, t.m08, - ); + return new Mat3(this); } /** @@ -793,16 +790,17 @@ export class Mat3 extends ValueType { public set (m00: number | Mat3 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, m06 = 0, m07 = 0, m08 = 1): Mat3 { + const self = this; if (typeof m00 === 'object') { - this.m00 = m00.m00; this.m01 = m00.m01; this.m02 = m00.m02; - this.m03 = m00.m03; this.m04 = m00.m04; this.m05 = m00.m05; - this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; + self.m00 = m00.m00; self.m01 = m00.m01; self.m02 = m00.m02; + self.m03 = m00.m03; self.m04 = m00.m04; self.m05 = m00.m05; + self.m06 = m00.m06; self.m07 = m00.m07; self.m08 = m00.m08; } else { - this.m00 = m00; this.m01 = m01; this.m02 = m02; - this.m03 = m03; this.m04 = m04; this.m05 = m05; - this.m06 = m06; this.m07 = m07; this.m08 = m08; + self.m00 = m00; self.m01 = m01; self.m02 = m02; + self.m03 = m03; self.m04 = m04; self.m05 = m05; + self.m06 = m06; self.m07 = m07; self.m08 = m08; } - return this; + return self; } /** @@ -813,17 +811,7 @@ export class Mat3 extends ValueType { * @return Returns `true' when the elements of both matrices are equal; otherwise returns `false'. */ public equals (other: Mat3, epsilon = EPSILON): boolean { - return ( - Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) - && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) - && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) - && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) - && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) - && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) - && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) - && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) - && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08)) - ); + return Mat3.equals(this, other, epsilon); } /** @@ -833,9 +821,7 @@ export class Mat3 extends ValueType { * @return Returns `true' when the elements of both matrices are equal; otherwise returns `false'. */ public strictEquals (other: Mat3): boolean { - return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 - && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 - && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08; + return Mat3.strictEquals(this, other); } /** @@ -858,16 +844,7 @@ export class Mat3 extends ValueType { * @return `this` */ public identity (): Mat3 { - this.m00 = 1; - this.m01 = 0; - this.m02 = 0; - this.m03 = 0; - this.m04 = 1; - this.m05 = 0; - this.m06 = 0; - this.m07 = 0; - this.m08 = 1; - return this; + return Mat3.identity(this); } /** @@ -875,14 +852,15 @@ export class Mat3 extends ValueType { * @zh 计算当前矩阵的转置矩阵。 */ public transpose (): Mat3 { - const a01 = this.m01; const a02 = this.m02; const a12 = this.m05; - this.m01 = this.m03; - this.m02 = this.m06; - this.m03 = a01; - this.m05 = this.m07; - this.m06 = a02; - this.m07 = a12; - return this; + const self = this; + const a01 = self.m01; const a02 = self.m02; const a12 = self.m05; + self.m01 = self.m03; + self.m02 = self.m06; + self.m03 = a01; + self.m05 = self.m07; + self.m06 = a02; + self.m07 = a12; + return self; } /** @@ -890,33 +868,7 @@ export class Mat3 extends ValueType { * @zh 计算当前矩阵的逆矩阵。注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ public invert (): Mat3 { - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; - const a10 = this.m03; const a11 = this.m04; const a12 = this.m05; - const a20 = this.m06; const a21 = this.m07; const a22 = this.m08; - - const b01 = a22 * a11 - a12 * a21; - const b11 = -a22 * a10 + a12 * a20; - const b21 = a21 * a10 - a11 * a20; - - // Calculate the determinant - let det = a00 * b01 + a01 * b11 + a02 * b21; - - if (det === 0) { - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); - return this; - } - det = 1.0 / det; - - this.m00 = b01 * det; - this.m01 = (-a22 * a01 + a02 * a21) * det; - this.m02 = (a12 * a01 - a02 * a11) * det; - this.m03 = b11 * det; - this.m04 = (a22 * a00 - a02 * a20) * det; - this.m05 = (-a12 * a00 + a02 * a10) * det; - this.m06 = b21 * det; - this.m07 = (-a21 * a00 + a01 * a20) * det; - this.m08 = (a11 * a00 - a01 * a10) * det; - return this; + return Mat3.invert(this, this); } /** @@ -925,11 +877,7 @@ export class Mat3 extends ValueType { * @return 当前矩阵的行列式。 */ public determinant (): number { - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; - const a10 = this.m03; const a11 = this.m04; const a12 = this.m05; - const a20 = this.m06; const a21 = this.m07; const a22 = this.m08; - - return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); + return Mat3.determinant(this); } /** @@ -938,16 +886,17 @@ export class Mat3 extends ValueType { * @param mat the second operand */ public add (mat: Mat3): Mat3 { - this.m00 += mat.m00; - this.m01 += mat.m01; - this.m02 += mat.m02; - this.m03 += mat.m03; - this.m04 += mat.m04; - this.m05 += mat.m05; - this.m06 += mat.m06; - this.m07 += mat.m07; - this.m08 += mat.m08; - return this; + const self = this; + self.m00 += mat.m00; + self.m01 += mat.m01; + self.m02 += mat.m02; + self.m03 += mat.m03; + self.m04 += mat.m04; + self.m05 += mat.m05; + self.m06 += mat.m06; + self.m07 += mat.m07; + self.m08 += mat.m08; + return self; } /** @@ -956,16 +905,17 @@ export class Mat3 extends ValueType { * @param mat the second operand */ public subtract (mat: Mat3): Mat3 { - this.m00 -= mat.m00; - this.m01 -= mat.m01; - this.m02 -= mat.m02; - this.m03 -= mat.m03; - this.m04 -= mat.m04; - this.m05 -= mat.m05; - this.m06 -= mat.m06; - this.m07 -= mat.m07; - this.m08 -= mat.m08; - return this; + const self = this; + self.m00 -= mat.m00; + self.m01 -= mat.m01; + self.m02 -= mat.m02; + self.m03 -= mat.m03; + self.m04 -= mat.m04; + self.m05 -= mat.m05; + self.m06 -= mat.m06; + self.m07 -= mat.m07; + self.m08 -= mat.m08; + return self; } /** @@ -974,26 +924,7 @@ export class Mat3 extends ValueType { * @param mat the second operand */ public multiply (mat: Mat3): Mat3 { - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; - const a10 = this.m03; const a11 = this.m04; const a12 = this.m05; - const a20 = this.m06; const a21 = this.m07; const a22 = this.m08; - - const b00 = mat.m00; const b01 = mat.m01; const b02 = mat.m02; - const b10 = mat.m03; const b11 = mat.m04; const b12 = mat.m05; - const b20 = mat.m06; const b21 = mat.m07; const b22 = mat.m08; - - this.m00 = b00 * a00 + b01 * a10 + b02 * a20; - this.m01 = b00 * a01 + b01 * a11 + b02 * a21; - this.m02 = b00 * a02 + b01 * a12 + b02 * a22; - - this.m03 = b10 * a00 + b11 * a10 + b12 * a20; - this.m04 = b10 * a01 + b11 * a11 + b12 * a21; - this.m05 = b10 * a02 + b11 * a12 + b12 * a22; - - this.m06 = b20 * a00 + b21 * a10 + b22 * a20; - this.m07 = b20 * a01 + b21 * a11 + b22 * a21; - this.m08 = b20 * a02 + b21 * a12 + b22 * a22; - return this; + return Mat3.multiply(this, this, mat); } /** @@ -1002,16 +933,17 @@ export class Mat3 extends ValueType { * @param scalar amount to scale the matrix's elements by */ public multiplyScalar (scalar: number): Mat3 { - this.m00 *= scalar; - this.m01 *= scalar; - this.m02 *= scalar; - this.m03 *= scalar; - this.m04 *= scalar; - this.m05 *= scalar; - this.m06 *= scalar; - this.m07 *= scalar; - this.m08 *= scalar; - return this; + const self = this; + self.m00 *= scalar; + self.m01 *= scalar; + self.m02 *= scalar; + self.m03 *= scalar; + self.m04 *= scalar; + self.m05 *= scalar; + self.m06 *= scalar; + self.m07 *= scalar; + self.m08 *= scalar; + return self; } /** @@ -1022,16 +954,17 @@ export class Mat3 extends ValueType { public scale (vec: Vec3): Mat3 { const x = vec.x; const y = vec.y; + const self = this; - this.m00 *= x; - this.m01 *= x; - this.m02 *= x; + self.m00 *= x; + self.m01 *= x; + self.m02 *= x; - this.m03 *= y; - this.m04 *= y; - this.m05 *= y; + self.m03 *= y; + self.m04 *= y; + self.m05 *= y; - return this; + return self; } /** @@ -1040,25 +973,26 @@ export class Mat3 extends ValueType { * @param rad radian of rotation */ public rotate (rad: number): Mat3 { - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; - const a10 = this.m03; const a11 = this.m04; const a12 = this.m05; - const a20 = this.m06; const a21 = this.m07; const a22 = this.m08; + const self = this; + const a00 = self.m00; const a01 = self.m01; const a02 = self.m02; + const a10 = self.m03; const a11 = self.m04; const a12 = self.m05; + const a20 = self.m06; const a21 = self.m07; const a22 = self.m08; const s = Math.sin(rad); const c = Math.cos(rad); - this.m00 = c * a00 + s * a10; - this.m01 = c * a01 + s * a11; - this.m02 = c * a02 + s * a12; + self.m00 = c * a00 + s * a10; + self.m01 = c * a01 + s * a11; + self.m02 = c * a02 + s * a12; - this.m03 = c * a10 - s * a00; - this.m04 = c * a11 - s * a01; - this.m05 = c * a12 - s * a02; + self.m03 = c * a10 - s * a00; + self.m04 = c * a11 - s * a01; + self.m05 = c * a12 - s * a02; - this.m06 = a20; - this.m07 = a21; - this.m08 = a22; - return this; + self.m06 = a20; + self.m07 = a21; + self.m08 = a22; + return self; } /** @@ -1083,18 +1017,20 @@ export class Mat3 extends ValueType { const wy = w * y2; const wz = w * z2; - this.m00 = 1 - yy - zz; - this.m03 = yx - wz; - this.m06 = zx + wy; + const self = this; + + self.m00 = 1 - yy - zz; + self.m03 = yx - wz; + self.m06 = zx + wy; - this.m01 = yx + wz; - this.m04 = 1 - xx - zz; - this.m07 = zy - wx; + self.m01 = yx + wz; + self.m04 = 1 - xx - zz; + self.m07 = zy - wx; - this.m02 = zx - wy; - this.m05 = zy + wx; - this.m08 = 1 - xx - yy; - return this; + self.m02 = zx - wy; + self.m05 = zy + wx; + self.m08 = 1 - xx - yy; + return self; } } diff --git a/cocos/core/math/mat4.ts b/cocos/core/math/mat4.ts index e3f41c29991..266e8990045 100644 --- a/cocos/core/math/mat4.ts +++ b/cocos/core/math/mat4.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-this-alias */ /* Copyright (c) 2018-2023 Xiamen Yaji Software Co., Ltd. @@ -49,6 +50,13 @@ export const preTransforms = Object.freeze([ * @zh 表示四维(4x4)矩阵。 */ +const abs = Math.abs; +const max = Math.max; +const sqrt = Math.sqrt; +const sin = Math.sin; +const cos = Math.cos; +const tan = Math.tan; + export class Mat4 extends ValueType { public static IDENTITY = Object.freeze(new Mat4()); @@ -150,6 +158,30 @@ export class Mat4 extends ValueType { return out; } + /** + * @en return an zero matrix. + * @zh 将目标赋值为0矩阵 + */ + public static zero (out: Out): Out { + out.m00 = 0; + out.m01 = 0; + out.m02 = 0; + out.m03 = 0; + out.m04 = 0; + out.m05 = 0; + out.m06 = 0; + out.m07 = 0; + out.m08 = 0; + out.m09 = 0; + out.m10 = 0; + out.m11 = 0; + out.m12 = 0; + out.m13 = 0; + out.m14 = 0; + out.m15 = 0; + return out; + } + /** * @en Transposes a matrix and save the results to out matrix * @zh 转置矩阵 @@ -218,11 +250,7 @@ export class Mat4 extends ValueType { let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (det === 0) { - out.m00 = 0; out.m01 = 0; out.m02 = 0; out.m03 = 0; - out.m04 = 0; out.m05 = 0; out.m06 = 0; out.m07 = 0; - out.m08 = 0; out.m09 = 0; out.m10 = 0; out.m11 = 0; - out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 0; - return out; + return Mat4.zero(out); } det = 1.0 / det; @@ -411,9 +439,9 @@ export class Mat4 extends ValueType { public static rotate (out: Out, a: Out, rad: number, axis: VecLike): Out | null { let x = axis.x; let y = axis.y; let z = axis.z; - let len = Math.sqrt(x * x + y * y + z * z); + let len = sqrt(x * x + y * y + z * z); - if (Math.abs(len) < EPSILON) { + if (abs(len) < EPSILON) { return null; } @@ -424,8 +452,8 @@ export class Mat4 extends ValueType { // ref: https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle - const s = Math.sin(rad); - const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); const t = 1 - c; const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; @@ -469,8 +497,8 @@ export class Mat4 extends ValueType { * @param rad Angle of rotation (in radians) */ public static rotateX (out: Out, a: Out, rad: number): Out { - const s = Math.sin(rad); - const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; @@ -512,8 +540,8 @@ export class Mat4 extends ValueType { public static rotateY (out: Out, a: Out, rad: number): Out { // ref: https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle - const s = Math.sin(rad); - const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; @@ -555,8 +583,8 @@ export class Mat4 extends ValueType { public static rotateZ (out: Out, a: Out, rad: number): Out { // ref: https://en.wikipedia.org/wiki/Rotation_matrix#Axis_and_angle - const s = Math.sin(rad); - const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; @@ -596,22 +624,10 @@ export class Mat4 extends ValueType { * @zh 计算位移矩阵 */ public static fromTranslation (out: Out, v: VecLike): Out { - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; - out.m05 = 1; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = 1; - out.m11 = 0; + Mat4.identity(out); out.m12 = v.x; out.m13 = v.y; out.m14 = v.z; - out.m15 = 1; return out; } @@ -620,22 +636,10 @@ export class Mat4 extends ValueType { * @zh 计算缩放矩阵 */ public static fromScaling (out: Out, v: VecLike): Out { + Mat4.identity(out); out.m00 = v.x; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; out.m05 = v.y; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; out.m10 = v.z; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; return out; } @@ -645,9 +649,9 @@ export class Mat4 extends ValueType { */ public static fromRotation (out: Out, rad: number, axis: VecLike): Out | null { let x = axis.x; let y = axis.y; let z = axis.z; - let len = Math.sqrt(x * x + y * y + z * z); + let len = sqrt(x * x + y * y + z * z); - if (Math.abs(len) < EPSILON) { + if (abs(len) < EPSILON) { return null; } @@ -656,8 +660,8 @@ export class Mat4 extends ValueType { y *= len; z *= len; - const s = Math.sin(rad); - const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); const t = 1 - c; // Perform rotation-specific matrix multiplication @@ -685,25 +689,15 @@ export class Mat4 extends ValueType { * @zh 计算绕 X 轴的旋转矩阵 */ public static fromXRotation (out: Out, rad: number): Out { - const s = Math.sin(rad); const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); + Mat4.identity(out); // Perform axis-specific matrix multiplication - out.m00 = 1; - out.m01 = 0; - out.m02 = 0; - out.m03 = 0; - out.m04 = 0; out.m05 = c; out.m06 = s; - out.m07 = 0; - out.m08 = 0; out.m09 = -s; out.m10 = c; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; return out; } @@ -712,25 +706,15 @@ export class Mat4 extends ValueType { * @zh 计算绕 Y 轴的旋转矩阵 */ public static fromYRotation (out: Out, rad: number): Out { - const s = Math.sin(rad); const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); + Mat4.identity(out); // Perform axis-specific matrix multiplication out.m00 = c; - out.m01 = 0; out.m02 = -s; - out.m03 = 0; - out.m04 = 0; - out.m05 = 1; - out.m06 = 0; - out.m07 = 0; out.m08 = s; - out.m09 = 0; out.m10 = c; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; return out; } @@ -739,25 +723,15 @@ export class Mat4 extends ValueType { * @zh 计算绕 Z 轴的旋转矩阵 */ public static fromZRotation (out: Out, rad: number): Out { - const s = Math.sin(rad); const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); + Mat4.identity(out); // Perform axis-specific matrix multiplication out.m00 = c; out.m01 = s; - out.m02 = 0; - out.m03 = 0; out.m04 = -s; out.m05 = c; - out.m06 = 0; - out.m07 = 0; - out.m08 = 0; - out.m09 = 0; - out.m10 = 1; - out.m11 = 0; - out.m12 = 0; - out.m13 = 0; - out.m14 = 0; - out.m15 = 1; return out; } @@ -830,9 +804,9 @@ export class Mat4 extends ValueType { const m08 = m3_1.m06 = mat.m08; const m09 = m3_1.m07 = mat.m09; const m10 = m3_1.m08 = mat.m10; - out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); - out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06); - out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10); + out.x = sqrt(m00 * m00 + m01 * m01 + m02 * m02); + out.y = sqrt(m04 * m04 + m05 * m05 + m06 * m06); + out.z = sqrt(m08 * m08 + m09 * m09 + m10 * m10); // account for refections if (Mat3.determinant(m3_1) < 0) { out.x *= -1; } return out; @@ -847,25 +821,25 @@ export class Mat4 extends ValueType { let S = 0; if (trace > 0) { - S = Math.sqrt(trace + 1.0) * 2; + S = sqrt(trace + 1.0) * 2; out.w = 0.25 * S; out.x = (mat.m06 - mat.m09) / S; out.y = (mat.m08 - mat.m02) / S; out.z = (mat.m01 - mat.m04) / S; } else if ((mat.m00 > mat.m05) && (mat.m00 > mat.m10)) { - S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2; + S = sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2; out.w = (mat.m06 - mat.m09) / S; out.x = 0.25 * S; out.y = (mat.m01 + mat.m04) / S; out.z = (mat.m08 + mat.m02) / S; } else if (mat.m05 > mat.m10) { - S = Math.sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2; + S = sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2; out.w = (mat.m08 - mat.m02) / S; out.x = (mat.m01 + mat.m04) / S; out.y = 0.25 * S; out.z = (mat.m06 + mat.m09) / S; } else { - S = Math.sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2; + S = sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2; out.w = (mat.m01 - mat.m04) / S; out.x = (mat.m08 + mat.m02) / S; out.y = (mat.m06 + mat.m09) / S; @@ -986,7 +960,7 @@ export class Mat4 extends ValueType { * @returns The receiving matrix */ public static fromSRT (out: Out, q: Quat, v: VecLike, s: VecLike): Out { - const x = q.x; const y = q.y; const z = q.z; const w = q.w; + const { x, y, z, w } = q; const x2 = x + x; const y2 = y + y; const z2 = z + z; @@ -1034,47 +1008,7 @@ export class Mat4 extends ValueType { * @deprecated Please use [[fromSRTOrigin]] instead. */ public static fromRTSOrigin (out: Out, q: Quat, v: VecLike, s: VecLike, o: VecLike): Out { - const x = q.x; const y = q.y; const z = q.z; const w = q.w; - const x2 = x + x; - const y2 = y + y; - const z2 = z + z; - - const xx = x * x2; - const xy = x * y2; - const xz = x * z2; - const yy = y * y2; - const yz = y * z2; - const zz = z * z2; - const wx = w * x2; - const wy = w * y2; - const wz = w * z2; - - const sx = s.x; - const sy = s.y; - const sz = s.z; - - const ox = o.x; - const oy = o.y; - const oz = o.z; - - out.m00 = (1 - (yy + zz)) * sx; - out.m01 = (xy + wz) * sx; - out.m02 = (xz - wy) * sx; - out.m03 = 0; - out.m04 = (xy - wz) * sy; - out.m05 = (1 - (xx + zz)) * sy; - out.m06 = (yz + wx) * sy; - out.m07 = 0; - out.m08 = (xz + wy) * sz; - out.m09 = (yz - wx) * sz; - out.m10 = (1 - (xx + yy)) * sz; - out.m11 = 0; - out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz); - out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz); - out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz); - out.m15 = 1; - - return out; + return Mat4.fromSRTOrigin(out, q, v, s, o); } /** @@ -1238,7 +1172,7 @@ export class Mat4 extends ValueType { out: Out, fov: number, aspect: number, near: number, far: number, isFOVY = true, minClipZ = -1, projectionSignY = 1, orientation = 0, ): Out { - const f = 1.0 / Math.tan(fov / 2); + const f = 1.0 / tan(fov / 2); const nf = 1 / (near - far); const x = isFOVY ? f / aspect : f; @@ -1340,7 +1274,7 @@ export class Mat4 extends ValueType { let z1 = eyey - centery; let z2 = eyez - centerz; - let len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + let len = 1 / sqrt(z0 * z0 + z1 * z1 + z2 * z2); z0 *= len; z1 *= len; z2 *= len; @@ -1348,7 +1282,7 @@ export class Mat4 extends ValueType { let x0 = upy * z2 - upz * z1; let x1 = upz * z0 - upx * z2; let x2 = upx * z1 - upy * z0; - len = 1 / Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + len = 1 / sqrt(x0 * x0 + x1 * x1 + x2 * x2); x0 *= len; x1 *= len; x2 *= len; @@ -1603,22 +1537,22 @@ export class Mat4 extends ValueType { // TAOCP vol.2, 3rd ed., s.4.2.4, p.213-225 // defines a 'close enough' relationship between u and v that scales for magnitude return ( - Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) - && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) - && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) - && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) - && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) - && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) - && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) - && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) - && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08)) - && Math.abs(a.m09 - b.m09) <= epsilon * Math.max(1.0, Math.abs(a.m09), Math.abs(b.m09)) - && Math.abs(a.m10 - b.m10) <= epsilon * Math.max(1.0, Math.abs(a.m10), Math.abs(b.m10)) - && Math.abs(a.m11 - b.m11) <= epsilon * Math.max(1.0, Math.abs(a.m11), Math.abs(b.m11)) - && Math.abs(a.m12 - b.m12) <= epsilon * Math.max(1.0, Math.abs(a.m12), Math.abs(b.m12)) - && Math.abs(a.m13 - b.m13) <= epsilon * Math.max(1.0, Math.abs(a.m13), Math.abs(b.m13)) - && Math.abs(a.m14 - b.m14) <= epsilon * Math.max(1.0, Math.abs(a.m14), Math.abs(b.m14)) - && Math.abs(a.m15 - b.m15) <= epsilon * Math.max(1.0, Math.abs(a.m15), Math.abs(b.m15)) + abs(a.m00 - b.m00) <= epsilon * max(1.0, abs(a.m00), abs(b.m00)) + && abs(a.m01 - b.m01) <= epsilon * max(1.0, abs(a.m01), abs(b.m01)) + && abs(a.m02 - b.m02) <= epsilon * max(1.0, abs(a.m02), abs(b.m02)) + && abs(a.m03 - b.m03) <= epsilon * max(1.0, abs(a.m03), abs(b.m03)) + && abs(a.m04 - b.m04) <= epsilon * max(1.0, abs(a.m04), abs(b.m04)) + && abs(a.m05 - b.m05) <= epsilon * max(1.0, abs(a.m05), abs(b.m05)) + && abs(a.m06 - b.m06) <= epsilon * max(1.0, abs(a.m06), abs(b.m06)) + && abs(a.m07 - b.m07) <= epsilon * max(1.0, abs(a.m07), abs(b.m07)) + && abs(a.m08 - b.m08) <= epsilon * max(1.0, abs(a.m08), abs(b.m08)) + && abs(a.m09 - b.m09) <= epsilon * max(1.0, abs(a.m09), abs(b.m09)) + && abs(a.m10 - b.m10) <= epsilon * max(1.0, abs(a.m10), abs(b.m10)) + && abs(a.m11 - b.m11) <= epsilon * max(1.0, abs(a.m11), abs(b.m11)) + && abs(a.m12 - b.m12) <= epsilon * max(1.0, abs(a.m12), abs(b.m12)) + && abs(a.m13 - b.m13) <= epsilon * max(1.0, abs(a.m13), abs(b.m13)) + && abs(a.m14 - b.m14) <= epsilon * max(1.0, abs(a.m14), abs(b.m14)) + && abs(a.m15 - b.m15) <= epsilon * max(1.0, abs(a.m15), abs(b.m15)) ); } @@ -1741,16 +1675,17 @@ export class Mat4 extends ValueType { m12 = 0, m13 = 0, m14 = 0, m15 = 1, ) { super(); + const self = this; if (typeof m00 === 'object') { - this.m00 = m00.m00; this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; - this.m04 = m00.m04; this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; - this.m08 = m00.m08; this.m09 = m00.m09; this.m10 = m00.m10; this.m11 = m00.m11; - this.m12 = m00.m12; this.m13 = m00.m13; this.m14 = m00.m14; this.m15 = m00.m15; + self.m00 = m00.m00; this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; + self.m04 = m00.m04; this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; + self.m08 = m00.m08; this.m09 = m00.m09; this.m10 = m00.m10; this.m11 = m00.m11; + self.m12 = m00.m12; this.m13 = m00.m13; this.m14 = m00.m14; this.m15 = m00.m15; } else { - this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; - this.m04 = m04; this.m05 = m05; this.m06 = m06; this.m07 = m07; - this.m08 = m08; this.m09 = m09; this.m10 = m10; this.m11 = m11; - this.m12 = m12; this.m13 = m13; this.m14 = m14; this.m15 = m15; + self.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; + self.m04 = m04; this.m05 = m05; this.m06 = m06; this.m07 = m07; + self.m08 = m08; this.m09 = m09; this.m10 = m10; this.m11 = m11; + self.m12 = m12; this.m13 = m13; this.m14 = m14; this.m15 = m15; } } @@ -1791,18 +1726,19 @@ export class Mat4 extends ValueType { m04 = 0, m05 = 1, m06 = 0, m07 = 0, m08 = 0, m09 = 0, m10 = 1, m11 = 0, m12 = 0, m13 = 0, m14 = 0, m15 = 1): Mat4 { + const self = this; if (typeof m00 === 'object') { - this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; this.m04 = m00.m04; - this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; - this.m09 = m00.m09; this.m10 = m00.m10; this.m11 = m00.m11; this.m12 = m00.m12; - this.m13 = m00.m13; this.m14 = m00.m14; this.m15 = m00.m15; this.m00 = m00.m00; + self.m01 = m00.m01; self.m02 = m00.m02; self.m03 = m00.m03; self.m04 = m00.m04; + self.m05 = m00.m05; self.m06 = m00.m06; self.m07 = m00.m07; self.m08 = m00.m08; + self.m09 = m00.m09; self.m10 = m00.m10; self.m11 = m00.m11; self.m12 = m00.m12; + self.m13 = m00.m13; self.m14 = m00.m14; self.m15 = m00.m15; self.m00 = m00.m00; } else { - this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; - this.m05 = m05; this.m06 = m06; this.m07 = m07; this.m08 = m08; - this.m09 = m09; this.m10 = m10; this.m11 = m11; this.m12 = m12; - this.m13 = m13; this.m14 = m14; this.m15 = m15; this.m00 = m00; + self.m01 = m01; self.m02 = m02; self.m03 = m03; self.m04 = m04; + self.m05 = m05; self.m06 = m06; self.m07 = m07; self.m08 = m08; + self.m09 = m09; self.m10 = m10; self.m11 = m11; self.m12 = m12; + self.m13 = m13; self.m14 = m14; self.m15 = m15; self.m00 = m00; } - return this; + return self; } /** @@ -1813,40 +1749,59 @@ export class Mat4 extends ValueType { * @return Returns `true' when the elements of both matrices are equal; otherwise returns `false'. */ public equals (other: Mat4, epsilon = EPSILON): boolean { - const hasInf = Math.abs(this.m00) === Infinity - || Math.abs(this.m01) === Infinity - || Math.abs(this.m02) === Infinity - || Math.abs(this.m03) === Infinity - || Math.abs(this.m04) === Infinity - || Math.abs(this.m05) === Infinity - || Math.abs(this.m06) === Infinity - || Math.abs(this.m07) === Infinity - || Math.abs(this.m08) === Infinity - || Math.abs(this.m09) === Infinity - || Math.abs(this.m10) === Infinity - || Math.abs(this.m11) === Infinity - || Math.abs(this.m12) === Infinity - || Math.abs(this.m13) === Infinity - || Math.abs(this.m14) === Infinity - || Math.abs(this.m15) === Infinity; + const inf = Infinity; + const self = this; + const m00 = self.m00; + const m01 = self.m01; + const m02 = self.m02; + const m03 = self.m03; + const m04 = self.m04; + const m05 = self.m05; + const m06 = self.m06; + const m07 = self.m07; + const m08 = self.m08; + const m09 = self.m09; + const m10 = self.m10; + const m11 = self.m11; + const m12 = self.m12; + const m13 = self.m13; + const m14 = self.m14; + const m15 = self.m15; + + const hasInf = abs(m00) === inf + || abs(m01) === inf + || abs(m02) === inf + || abs(m03) === inf + || abs(m04) === inf + || abs(m05) === inf + || abs(m06) === inf + || abs(m07) === inf + || abs(m08) === inf + || abs(m09) === inf + || abs(m10) === inf + || abs(m11) === inf + || abs(m12) === inf + || abs(m13) === inf + || abs(m14) === inf + || abs(m15) === inf; return (!hasInf - && Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) - && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) - && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) - && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) - && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) - && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) - && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) - && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) - && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08)) - && Math.abs(this.m09 - other.m09) <= epsilon * Math.max(1.0, Math.abs(this.m09), Math.abs(other.m09)) - && Math.abs(this.m10 - other.m10) <= epsilon * Math.max(1.0, Math.abs(this.m10), Math.abs(other.m10)) - && Math.abs(this.m11 - other.m11) <= epsilon * Math.max(1.0, Math.abs(this.m11), Math.abs(other.m11)) - && Math.abs(this.m12 - other.m12) <= epsilon * Math.max(1.0, Math.abs(this.m12), Math.abs(other.m12)) - && Math.abs(this.m13 - other.m13) <= epsilon * Math.max(1.0, Math.abs(this.m13), Math.abs(other.m13)) - && Math.abs(this.m14 - other.m14) <= epsilon * Math.max(1.0, Math.abs(this.m14), Math.abs(other.m14)) - && Math.abs(this.m15 - other.m15) <= epsilon * Math.max(1.0, Math.abs(this.m15), Math.abs(other.m15)) + && abs(m00 - other.m00) <= epsilon * max(1.0, abs(m00), abs(other.m00)) + && abs(m01 - other.m01) <= epsilon * max(1.0, abs(m01), abs(other.m01)) + && abs(m02 - other.m02) <= epsilon * max(1.0, abs(m02), abs(other.m02)) + && abs(m03 - other.m03) <= epsilon * max(1.0, abs(m03), abs(other.m03)) + && abs(m04 - other.m04) <= epsilon * max(1.0, abs(m04), abs(other.m04)) + && abs(m05 - other.m05) <= epsilon * max(1.0, abs(m05), abs(other.m05)) + && abs(m06 - other.m06) <= epsilon * max(1.0, abs(m06), abs(other.m06)) + && abs(m07 - other.m07) <= epsilon * max(1.0, abs(m07), abs(other.m07)) + && abs(m08 - other.m08) <= epsilon * max(1.0, abs(m08), abs(other.m08)) + && abs(m09 - other.m09) <= epsilon * max(1.0, abs(m09), abs(other.m09)) + && abs(m10 - other.m10) <= epsilon * max(1.0, abs(m10), abs(other.m10)) + && abs(m11 - other.m11) <= epsilon * max(1.0, abs(m11), abs(other.m11)) + && abs(m12 - other.m12) <= epsilon * max(1.0, abs(m12), abs(other.m12)) + && abs(m13 - other.m13) <= epsilon * max(1.0, abs(m13), abs(other.m13)) + && abs(m14 - other.m14) <= epsilon * max(1.0, abs(m14), abs(other.m14)) + && abs(m15 - other.m15) <= epsilon * max(1.0, abs(m15), abs(other.m15)) ); } @@ -1857,10 +1812,11 @@ export class Mat4 extends ValueType { * @return Returns `true' when the elements of both matrices are equal; otherwise returns `false'. */ public strictEquals (other: Mat4): boolean { - return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 - && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 - && this.m08 === other.m08 && this.m09 === other.m09 && this.m10 === other.m10 && this.m11 === other.m11 - && this.m12 === other.m12 && this.m13 === other.m13 && this.m14 === other.m14 && this.m15 === other.m15; + const self = this; + return self.m00 === other.m00 && self.m01 === other.m01 && self.m02 === other.m02 && self.m03 === other.m03 + && self.m04 === other.m04 && self.m05 === other.m05 && self.m06 === other.m06 && self.m07 === other.m07 + && self.m08 === other.m08 && self.m09 === other.m09 && self.m10 === other.m10 && self.m11 === other.m11 + && self.m12 === other.m12 && self.m13 === other.m13 && self.m14 === other.m14 && self.m15 === other.m15; } /** @@ -1883,23 +1839,7 @@ export class Mat4 extends ValueType { * @return `this` */ public identity (): Mat4 { - this.m00 = 1; - this.m01 = 0; - this.m02 = 0; - this.m03 = 0; - this.m04 = 0; - this.m05 = 1; - this.m06 = 0; - this.m07 = 0; - this.m08 = 0; - this.m09 = 0; - this.m10 = 1; - this.m11 = 0; - this.m12 = 0; - this.m13 = 0; - this.m14 = 0; - this.m15 = 1; - return this; + return Mat4.identity(this); } /** @@ -1908,23 +1848,7 @@ export class Mat4 extends ValueType { * @return `this` */ public zero (): Mat4 { - this.m00 = 0; - this.m01 = 0; - this.m02 = 0; - this.m03 = 0; - this.m04 = 0; - this.m05 = 0; - this.m06 = 0; - this.m07 = 0; - this.m08 = 0; - this.m09 = 0; - this.m10 = 0; - this.m11 = 0; - this.m12 = 0; - this.m13 = 0; - this.m14 = 0; - this.m15 = 0; - return this; + return Mat4.zero(this); } /** @@ -1932,20 +1856,22 @@ export class Mat4 extends ValueType { * @zh 计算当前矩阵的转置矩阵。 */ public transpose (): Mat4 { - const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a12 = this.m06; const a13 = this.m07; const a23 = this.m11; - this.m01 = this.m04; - this.m02 = this.m08; - this.m03 = this.m12; - this.m04 = a01; - this.m06 = this.m09; - this.m07 = this.m13; - this.m08 = a02; - this.m09 = a12; - this.m11 = this.m14; - this.m12 = a03; - this.m13 = a13; - this.m14 = a23; - return this; + const self = this; + const a01 = self.m01; const a02 = self.m02; const a03 = self.m03; + const a12 = self.m06; const a13 = self.m07; const a23 = self.m11; + self.m01 = self.m04; + self.m02 = self.m08; + self.m03 = self.m12; + self.m04 = a01; + self.m06 = self.m09; + self.m07 = self.m13; + self.m08 = a02; + self.m09 = a12; + self.m11 = self.m14; + self.m12 = a03; + self.m13 = a13; + self.m14 = a23; + return self; } /** @@ -1953,10 +1879,11 @@ export class Mat4 extends ValueType { * @zh 计算当前矩阵的逆矩阵。注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ public invert (): Mat4 { - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; - const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; - const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; - const a30 = this.m12; const a31 = this.m13; const a32 = this.m14; const a33 = this.m15; + const self = this; + const a00 = self.m00; const a01 = self.m01; const a02 = self.m02; const a03 = self.m03; + const a10 = self.m04; const a11 = self.m05; const a12 = self.m06; const a13 = self.m07; + const a20 = self.m08; const a21 = self.m09; const a22 = self.m10; const a23 = self.m11; + const a30 = self.m12; const a31 = self.m13; const a32 = self.m14; const a33 = self.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; @@ -1975,29 +1902,29 @@ export class Mat4 extends ValueType { let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (det === 0) { - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - return this; + self.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + return self; } det = 1.0 / det; - this.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; - this.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; - this.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; - this.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; - this.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; - this.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; - this.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; - this.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; - this.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; - this.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; - this.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; - this.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; - this.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; - this.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; - this.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; - this.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; + self.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; + self.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; + self.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; + self.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; + self.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; + self.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; + self.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; + self.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; + self.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; + self.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; + self.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; + self.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; + self.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; + self.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; + self.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; + self.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; - return this; + return self; } /** @@ -2006,10 +1933,11 @@ export class Mat4 extends ValueType { * @return 当前矩阵的行列式。 */ public determinant (): number { - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; - const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; - const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; - const a30 = this.m12; const a31 = this.m13; const a32 = this.m14; const a33 = this.m15; + const self = this; + const a00 = self.m00; const a01 = self.m01; const a02 = self.m02; const a03 = self.m03; + const a10 = self.m04; const a11 = self.m05; const a12 = self.m06; const a13 = self.m07; + const a20 = self.m08; const a21 = self.m09; const a22 = self.m10; const a23 = self.m11; + const a30 = self.m12; const a31 = self.m13; const a32 = self.m14; const a33 = self.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; @@ -2034,23 +1962,24 @@ export class Mat4 extends ValueType { * @param mat the second operand */ public add (mat: Mat4): Mat4 { - this.m00 += mat.m00; - this.m01 += mat.m01; - this.m02 += mat.m02; - this.m03 += mat.m03; - this.m04 += mat.m04; - this.m05 += mat.m05; - this.m06 += mat.m06; - this.m07 += mat.m07; - this.m08 += mat.m08; - this.m09 += mat.m09; - this.m10 += mat.m10; - this.m11 += mat.m11; - this.m12 += mat.m12; - this.m13 += mat.m13; - this.m14 += mat.m14; - this.m15 += mat.m15; - return this; + const self = this; + self.m00 += mat.m00; + self.m01 += mat.m01; + self.m02 += mat.m02; + self.m03 += mat.m03; + self.m04 += mat.m04; + self.m05 += mat.m05; + self.m06 += mat.m06; + self.m07 += mat.m07; + self.m08 += mat.m08; + self.m09 += mat.m09; + self.m10 += mat.m10; + self.m11 += mat.m11; + self.m12 += mat.m12; + self.m13 += mat.m13; + self.m14 += mat.m14; + self.m15 += mat.m15; + return self; } /** @@ -2059,23 +1988,24 @@ export class Mat4 extends ValueType { * @param mat the second operand */ public subtract (mat: Mat4): Mat4 { - this.m00 -= mat.m00; - this.m01 -= mat.m01; - this.m02 -= mat.m02; - this.m03 -= mat.m03; - this.m04 -= mat.m04; - this.m05 -= mat.m05; - this.m06 -= mat.m06; - this.m07 -= mat.m07; - this.m08 -= mat.m08; - this.m09 -= mat.m09; - this.m10 -= mat.m10; - this.m11 -= mat.m11; - this.m12 -= mat.m12; - this.m13 -= mat.m13; - this.m14 -= mat.m14; - this.m15 -= mat.m15; - return this; + const self = this; + self.m00 -= mat.m00; + self.m01 -= mat.m01; + self.m02 -= mat.m02; + self.m03 -= mat.m03; + self.m04 -= mat.m04; + self.m05 -= mat.m05; + self.m06 -= mat.m06; + self.m07 -= mat.m07; + self.m08 -= mat.m08; + self.m09 -= mat.m09; + self.m10 -= mat.m10; + self.m11 -= mat.m11; + self.m12 -= mat.m12; + self.m13 -= mat.m13; + self.m14 -= mat.m14; + self.m15 -= mat.m15; + return self; } /** @@ -2084,36 +2014,7 @@ export class Mat4 extends ValueType { * @param mat the second operand */ public multiply (mat: Mat4): Mat4 { - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; - const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; - const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; - const a30 = this.m12; const a31 = this.m13; const a32 = this.m14; const a33 = this.m15; - - // Cache only the current line of the second matrix - let b0 = mat.m00; let b1 = mat.m01; let b2 = mat.m02; let b3 = mat.m03; - this.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - this.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - this.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - this.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = mat.m04; b1 = mat.m05; b2 = mat.m06; b3 = mat.m07; - this.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - this.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - this.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - this.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = mat.m08; b1 = mat.m09; b2 = mat.m10; b3 = mat.m11; - this.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - this.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - this.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - this.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - - b0 = mat.m12; b1 = mat.m13; b2 = mat.m14; b3 = mat.m15; - this.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - this.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - this.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - this.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - return this; + return Mat4.multiply(this, this, mat); } /** @@ -2122,23 +2023,24 @@ export class Mat4 extends ValueType { * @param scalar amount to scale the matrix's elements by */ public multiplyScalar (scalar: number): Mat4 { - this.m00 *= scalar; - this.m01 *= scalar; - this.m02 *= scalar; - this.m03 *= scalar; - this.m04 *= scalar; - this.m05 *= scalar; - this.m06 *= scalar; - this.m07 *= scalar; - this.m08 *= scalar; - this.m09 *= scalar; - this.m10 *= scalar; - this.m11 *= scalar; - this.m12 *= scalar; - this.m13 *= scalar; - this.m14 *= scalar; - this.m15 *= scalar; - return this; + const self = this; + self.m00 *= scalar; + self.m01 *= scalar; + self.m02 *= scalar; + self.m03 *= scalar; + self.m04 *= scalar; + self.m05 *= scalar; + self.m06 *= scalar; + self.m07 *= scalar; + self.m08 *= scalar; + self.m09 *= scalar; + self.m10 *= scalar; + self.m11 *= scalar; + self.m12 *= scalar; + self.m13 *= scalar; + self.m14 *= scalar; + self.m15 *= scalar; + return self; } /** @@ -2162,16 +2064,17 @@ export class Mat4 extends ValueType { */ public transform (vec: Vec3): Mat4 { const { x, y, z } = vec; - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; - const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; - const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; + const self = this; + const a00 = self.m00; const a01 = self.m01; const a02 = self.m02; const a03 = self.m03; + const a10 = self.m04; const a11 = self.m05; const a12 = self.m06; const a13 = self.m07; + const a20 = self.m08; const a21 = self.m09; const a22 = self.m10; const a23 = self.m11; - this.m12 = a00 * x + a10 * y + a20 * z + this.m12; - this.m13 = a01 * x + a11 * y + a21 * z + this.m13; - this.m14 = a02 * x + a12 * y + a22 * z + this.m14; - this.m15 = a03 * x + a13 * y + a23 * z + this.m15; + self.m12 = a00 * x + a10 * y + a20 * z + self.m12; + self.m13 = a01 * x + a11 * y + a21 * z + self.m13; + self.m14 = a02 * x + a12 * y + a22 * z + self.m14; + self.m15 = a03 * x + a13 * y + a23 * z + self.m15; - return this; + return self; } /** @@ -2180,20 +2083,21 @@ export class Mat4 extends ValueType { * @param vec vector to scale by */ public scale (vec: Vec3): Mat4 { - const x = vec.x; const y = vec.y; const z = vec.z; - this.m00 *= x; - this.m01 *= x; - this.m02 *= x; - this.m03 *= x; - this.m04 *= y; - this.m05 *= y; - this.m06 *= y; - this.m07 *= y; - this.m08 *= z; - this.m09 *= z; - this.m10 *= z; - this.m11 *= z; - return this; + const { x, y, z } = vec; + const self = this; + self.m00 *= x; + self.m01 *= x; + self.m02 *= x; + self.m03 *= x; + self.m04 *= y; + self.m05 *= y; + self.m06 *= y; + self.m07 *= y; + self.m08 *= z; + self.m09 *= z; + self.m10 *= z; + self.m11 *= z; + return self; } /** @@ -2205,9 +2109,9 @@ export class Mat4 extends ValueType { public rotate (rad: number, axis: Vec3): Mat4 | null { let x = axis.x; let y = axis.y; let z = axis.z; - let len = Math.sqrt(x * x + y * y + z * z); + let len = sqrt(x * x + y * y + z * z); - if (Math.abs(len) < EPSILON) { + if (abs(len) < EPSILON) { return null; } @@ -2216,13 +2120,14 @@ export class Mat4 extends ValueType { y *= len; z *= len; - const s = Math.sin(rad); - const c = Math.cos(rad); + const s = sin(rad); + const c = cos(rad); const t = 1 - c; - const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; - const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; - const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; + const self = this; + const a00 = self.m00; const a01 = self.m01; const a02 = self.m02; const a03 = self.m03; + const a10 = self.m04; const a11 = self.m05; const a12 = self.m06; const a13 = self.m07; + const a20 = self.m08; const a21 = self.m09; const a22 = self.m10; const a23 = self.m11; // Construct the elements of the rotation matrix const b00 = x * x * t + c; const b01 = y * x * t + z * s; const b02 = z * x * t - y * s; @@ -2230,20 +2135,20 @@ export class Mat4 extends ValueType { const b20 = x * z * t + y * s; const b21 = y * z * t - x * s; const b22 = z * z * t + c; // Perform rotation-specific matrix multiplication - this.m00 = a00 * b00 + a10 * b01 + a20 * b02; - this.m01 = a01 * b00 + a11 * b01 + a21 * b02; - this.m02 = a02 * b00 + a12 * b01 + a22 * b02; - this.m03 = a03 * b00 + a13 * b01 + a23 * b02; - this.m04 = a00 * b10 + a10 * b11 + a20 * b12; - this.m05 = a01 * b10 + a11 * b11 + a21 * b12; - this.m06 = a02 * b10 + a12 * b11 + a22 * b12; - this.m07 = a03 * b10 + a13 * b11 + a23 * b12; - this.m08 = a00 * b20 + a10 * b21 + a20 * b22; - this.m09 = a01 * b20 + a11 * b21 + a21 * b22; - this.m10 = a02 * b20 + a12 * b21 + a22 * b22; - this.m11 = a03 * b20 + a13 * b21 + a23 * b22; + self.m00 = a00 * b00 + a10 * b01 + a20 * b02; + self.m01 = a01 * b00 + a11 * b01 + a21 * b02; + self.m02 = a02 * b00 + a12 * b01 + a22 * b02; + self.m03 = a03 * b00 + a13 * b01 + a23 * b02; + self.m04 = a00 * b10 + a10 * b11 + a20 * b12; + self.m05 = a01 * b10 + a11 * b11 + a21 * b12; + self.m06 = a02 * b10 + a12 * b11 + a22 * b12; + self.m07 = a03 * b10 + a13 * b11 + a23 * b12; + self.m08 = a00 * b20 + a10 * b21 + a20 * b22; + self.m09 = a01 * b20 + a11 * b21 + a21 * b22; + self.m10 = a02 * b20 + a12 * b21 + a22 * b22; + self.m11 = a03 * b20 + a13 * b21 + a23 * b22; - return this; + return self; } /** @@ -2265,18 +2170,19 @@ export class Mat4 extends ValueType { * @param out Vector to receive scale component */ public getScale (out: Vec3): Vec3 { - const m00 = m3_1.m00 = this.m00; - const m01 = m3_1.m01 = this.m01; - const m02 = m3_1.m02 = this.m02; - const m04 = m3_1.m03 = this.m04; - const m05 = m3_1.m04 = this.m05; - const m06 = m3_1.m05 = this.m06; - const m08 = m3_1.m06 = this.m08; - const m09 = m3_1.m07 = this.m09; - const m10 = m3_1.m08 = this.m10; - out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); - out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06); - out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10); + const self = this; + const m00 = m3_1.m00 = self.m00; + const m01 = m3_1.m01 = self.m01; + const m02 = m3_1.m02 = self.m02; + const m04 = m3_1.m03 = self.m04; + const m05 = m3_1.m04 = self.m05; + const m06 = m3_1.m05 = self.m06; + const m08 = m3_1.m06 = self.m08; + const m09 = m3_1.m07 = self.m09; + const m10 = m3_1.m08 = self.m10; + out.x = sqrt(m00 * m00 + m01 * m01 + m02 * m02); + out.y = sqrt(m04 * m04 + m05 * m05 + m06 * m06); + out.z = sqrt(m08 * m08 + m09 * m09 + m10 * m10); // account for reflections if (Mat3.determinant(m3_1) < 0) { out.x *= -1; } return out; @@ -2288,19 +2194,20 @@ export class Mat4 extends ValueType { * @param out Vector to receive rotation component */ public getRotation (out: Quat): Quat { + const self = this; // Extract rotation matrix first - const sx = Vec3.set(v3_1, this.m00, this.m01, this.m02).length(); - const sy = Vec3.set(v3_1, this.m04, this.m05, this.m06).length(); - const sz = Vec3.set(v3_1, this.m08, this.m09, this.m10).length(); - m3_1.m00 = this.m00 / sx; - m3_1.m01 = this.m01 / sx; - m3_1.m02 = this.m02 / sx; - m3_1.m03 = this.m04 / sy; - m3_1.m04 = this.m05 / sy; - m3_1.m05 = this.m06 / sy; - m3_1.m06 = this.m08 / sz; - m3_1.m07 = this.m09 / sz; - m3_1.m08 = this.m10 / sz; + const sx = Vec3.set(v3_1, self.m00, self.m01, self.m02).length(); + const sy = Vec3.set(v3_1, self.m04, self.m05, self.m06).length(); + const sz = Vec3.set(v3_1, self.m08, self.m09, self.m10).length(); + m3_1.m00 = self.m00 / sx; + m3_1.m01 = self.m01 / sx; + m3_1.m02 = self.m02 / sx; + m3_1.m03 = self.m04 / sy; + m3_1.m04 = self.m05 / sy; + m3_1.m05 = self.m06 / sy; + m3_1.m06 = self.m08 / sz; + m3_1.m07 = self.m09 / sz; + m3_1.m08 = self.m10 / sz; const det = Mat3.determinant(m3_1); if (det < 0) { m3_1.m00 *= -1; @@ -2322,42 +2229,7 @@ export class Mat4 extends ValueType { * @deprecated Since 3.8.0, please use [[fromSRT]] instead */ public fromRTS (q: Quat, v: Vec3, s: Vec3): Mat4 { - const x = q.x; const y = q.y; const z = q.z; const w = q.w; - const x2 = x + x; - const y2 = y + y; - const z2 = z + z; - - const xx = x * x2; - const xy = x * y2; - const xz = x * z2; - const yy = y * y2; - const yz = y * z2; - const zz = z * z2; - const wx = w * x2; - const wy = w * y2; - const wz = w * z2; - const sx = s.x; - const sy = s.y; - const sz = s.z; - - this.m00 = (1 - (yy + zz)) * sx; - this.m01 = (xy + wz) * sx; - this.m02 = (xz - wy) * sx; - this.m03 = 0; - this.m04 = (xy - wz) * sy; - this.m05 = (1 - (xx + zz)) * sy; - this.m06 = (yz + wx) * sy; - this.m07 = 0; - this.m08 = (xz + wy) * sz; - this.m09 = (yz - wx) * sz; - this.m10 = (1 - (xx + yy)) * sz; - this.m11 = 0; - this.m12 = v.x; - this.m13 = v.y; - this.m14 = v.z; - this.m15 = 1; - - return this; + return Mat4.fromSRT(this, q, v, s); } /** @@ -2369,42 +2241,7 @@ export class Mat4 extends ValueType { * @return `this` */ public fromSRT (q: Quat, v: Vec3, s: Vec3): Mat4 { - const x = q.x; const y = q.y; const z = q.z; const w = q.w; - const x2 = x + x; - const y2 = y + y; - const z2 = z + z; - - const xx = x * x2; - const xy = x * y2; - const xz = x * z2; - const yy = y * y2; - const yz = y * z2; - const zz = z * z2; - const wx = w * x2; - const wy = w * y2; - const wz = w * z2; - const sx = s.x; - const sy = s.y; - const sz = s.z; - - this.m00 = (1 - (yy + zz)) * sx; - this.m01 = (xy + wz) * sx; - this.m02 = (xz - wy) * sx; - this.m03 = 0; - this.m04 = (xy - wz) * sy; - this.m05 = (1 - (xx + zz)) * sy; - this.m06 = (yz + wx) * sy; - this.m07 = 0; - this.m08 = (xz + wy) * sz; - this.m09 = (yz - wx) * sz; - this.m10 = (1 - (xx + yy)) * sz; - this.m11 = 0; - this.m12 = v.x; - this.m13 = v.y; - this.m14 = v.z; - this.m15 = 1; - - return this; + return Mat4.fromSRT(this, q, v, s); } /** @@ -2414,42 +2251,7 @@ export class Mat4 extends ValueType { * @return `this` */ public fromQuat (q: Quat): Mat4 { - const x = q.x; const y = q.y; const z = q.z; const w = q.w; - const x2 = x + x; - const y2 = y + y; - const z2 = z + z; - - const xx = x * x2; - const yx = y * x2; - const yy = y * y2; - const zx = z * x2; - const zy = z * y2; - const zz = z * z2; - const wx = w * x2; - const wy = w * y2; - const wz = w * z2; - - this.m00 = 1 - yy - zz; - this.m01 = yx + wz; - this.m02 = zx - wy; - this.m03 = 0; - - this.m04 = yx - wz; - this.m05 = 1 - xx - zz; - this.m06 = zy + wx; - this.m07 = 0; - - this.m08 = zx + wy; - this.m09 = zy - wx; - this.m10 = 1 - xx - yy; - this.m11 = 0; - - this.m12 = 0; - this.m13 = 0; - this.m14 = 0; - this.m15 = 1; - - return this; + return Mat4.fromQuat(this, q); } } diff --git a/cocos/core/math/math-native-ext.ts b/cocos/core/math/math-native-ext.ts index 5c37004313e..5c19c1cbfed 100644 --- a/cocos/core/math/math-native-ext.ts +++ b/cocos/core/math/math-native-ext.ts @@ -29,19 +29,6 @@ import { Vec4 } from './vec4'; import { Quat } from './quat'; import { Color } from './color'; -const defineAttr = (proto: any, name: string, offset: number): void => { - Object.defineProperty(proto, name, { - configurable: true, - enumerable: true, - get (): any { - return this._data()[offset]; - }, - set (v: number): void { - this._data()[offset] = v; - }, - }); -}; - export enum MathType { VEC2 = 0, VEC3, @@ -54,32 +41,45 @@ export enum MathType { COLOR, } -function extendType (proto: any, parentProto: any, typ: MathType): void { - proto._data = function _data (): Float32Array { - if (!this.__data) { - this.__data = new Float32Array(this.underlyingData() as ArrayBuffer); // underlyingData is a JSB method. - } - return this.__data as Float32Array; - }; - Object.setPrototypeOf(proto, parentProto as object); - Object.defineProperty(proto, 'type', { configurable: true, enumerable: true, writable: false, value: typ }); -} - -function inheritCCClass (ctor: Constructor, parentCtor: Constructor): void { - for (const attrName of ['__cid__', '__classname__']) { - Object.defineProperty(ctor.prototype, attrName, { - value: parentCtor.prototype[attrName], - writable: false, - enumerable: false, +if (NATIVE) { + const defineAttr = (proto: any, name: string, offset: number): void => { + Object.defineProperty(proto, name, { configurable: true, + enumerable: true, + get (): any { + return this._data()[offset]; + }, + set (v: number): void { + this._data()[offset] = v; + }, }); - } - for (const staticKey of ['__attrs__', '__props__', '__values__']) { - ctor[staticKey] = parentCtor[staticKey]; - } -} + }; + + const extendType = (proto: any, parentProto: any, typ: MathType): void => { + proto._data = function _data (): Float32Array { + if (!this.__data) { + this.__data = new Float32Array(this.underlyingData() as ArrayBuffer); // underlyingData is a JSB method. + } + return this.__data as Float32Array; + }; + Object.setPrototypeOf(proto, parentProto as object); + Object.defineProperty(proto, 'type', { configurable: true, enumerable: true, writable: false, value: typ }); + }; + + const inheritCCClass = (ctor: Constructor, parentCtor: Constructor): void => { + for (const attrName of ['__cid__', '__classname__']) { + Object.defineProperty(ctor.prototype, attrName, { + value: parentCtor.prototype[attrName], + writable: false, + enumerable: false, + configurable: true, + }); + } + for (const staticKey of ['__attrs__', '__props__', '__values__']) { + ctor[staticKey] = parentCtor[staticKey]; + } + }; -if (NATIVE) { extendType(jsb.Mat4.prototype, Mat4.prototype, MathType.MAT4); for (let i = 0; i < 16; i++) { diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index d6d67cc778c..7687ba113fb 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-this-alias */ /* Copyright (c) 2018-2023 Xiamen Yaji Software Co., Ltd. @@ -33,6 +34,18 @@ import { EPSILON, toDegree } from './utils'; import { Vec3 } from './vec3'; import { legacyCC } from '../global-exports'; +const abs = Math.abs; +const max = Math.max; +const min = Math.min; +const PI = Math.PI; +const acos = Math.acos; +const sin = Math.sin; +const cos = Math.cos; +const sqrt = Math.sqrt; +const atan2 = Math.atan2; +const asin = Math.asin; +const sign = Math.sign; + /** * @en quaternion * @zh 四元数 @@ -96,7 +109,7 @@ export class Quat extends ValueType { Vec3.cross(v3_1, Vec3.UNIT_Y, a); } Vec3.normalize(v3_1, v3_1); - Quat.fromAxisAngle(out, v3_1, Math.PI); + Quat.fromAxisAngle(out, v3_1, PI); return out; } else if (dot > 0.999999) { out.x = 0; @@ -122,8 +135,8 @@ export class Quat extends ValueType { * @return radian of rotation */ public static getAxisAngle (outAxis: VecLike, q: Out): number { - const rad = Math.acos(q.w) * 2.0; - const s = Math.sin(rad / 2.0); + const rad = acos(q.w) * 2.0; + const s = sin(rad / 2.0); if (s !== 0.0) { outAxis.x = q.x / s; outAxis.y = q.y / s; @@ -189,8 +202,8 @@ export class Quat extends ValueType { public static rotateX (out: Out, a: Out, rad: number): Out { rad *= 0.5; - const bx = Math.sin(rad); - const bw = Math.cos(rad); + const bx = sin(rad); + const bw = cos(rad); const { x, y, z, w } = a; out.x = x * bw + w * bx; @@ -208,8 +221,8 @@ export class Quat extends ValueType { public static rotateY (out: Out, a: Out, rad: number): Out { rad *= 0.5; - const by = Math.sin(rad); - const bw = Math.cos(rad); + const by = sin(rad); + const bw = cos(rad); const { x, y, z, w } = a; out.x = x * bw - z * by; @@ -227,8 +240,8 @@ export class Quat extends ValueType { public static rotateZ (out: Out, a: Out, rad: number): Out { rad *= 0.5; - const bz = Math.sin(rad); - const bw = Math.cos(rad); + const bz = sin(rad); + const bw = cos(rad); const { x, y, z, w } = a; out.x = x * bw + y * bz; @@ -274,7 +287,7 @@ export class Quat extends ValueType { out.x = a.x; out.y = a.y; out.z = a.z; - out.w = Math.sqrt(Math.abs(1.0 - a.x * a.x - a.y * a.y - a.z * a.z)); + out.w = sqrt(abs(1.0 - a.x * a.x - a.y * a.y - a.z * a.z)); return out; } @@ -327,10 +340,10 @@ export class Quat extends ValueType { // calculate coefficients if ((1.0 - cosom) > 0.000001) { // standard case (slerp) - const omega = Math.acos(cosom); - const sinom = Math.sin(omega); - scale0 = Math.sin((1.0 - t) * omega) / sinom; - scale1 = Math.sin(t * omega) / sinom; + const omega = acos(cosom); + const sinom = sin(omega); + scale0 = sin((1.0 - t) * omega) / sinom; + scale1 = sin(t * omega) / sinom; } else { // "from" and "to" quaternions are very close // ... so we can do a linear interpolation @@ -398,7 +411,7 @@ export class Quat extends ValueType { * @zh 求四元数长度 */ public static len (a: Out): number { - return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); + return sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); } /** @@ -416,7 +429,7 @@ export class Quat extends ValueType { public static normalize (out: Out, a: Out): Out { let len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; if (len > 0) { - len = 1 / Math.sqrt(len); + len = 1 / sqrt(len); out.x = a.x * len; out.y = a.y * len; out.z = a.z * len; @@ -461,11 +474,11 @@ export class Quat extends ValueType { */ public static fromAxisAngle (out: Out, axis: VecLike, rad: number): Out { rad *= 0.5; - const s = Math.sin(rad); + const s = sin(rad); out.x = s * axis.x; out.y = s * axis.y; out.z = s * axis.z; - out.w = Math.cos(rad); + out.w = cos(rad); return out; } @@ -500,7 +513,7 @@ export class Quat extends ValueType { biggestIndex = 3; } - const biggestVal = Math.sqrt(fourBiggestSquaredMinus1 + 1) * 0.5; + const biggestVal = sqrt(fourBiggestSquaredMinus1 + 1) * 0.5; const mult = 0.25 / biggestVal; switch (biggestIndex) { case 0: @@ -546,12 +559,12 @@ export class Quat extends ValueType { y *= halfToRad; z *= halfToRad; - const sx = Math.sin(x); - const cx = Math.cos(x); - const sy = Math.sin(y); - const cy = Math.cos(y); - const sz = Math.sin(z); - const cz = Math.cos(z); + const sx = sin(x); + const cx = cos(x); + const sy = sin(y); + const cy = cos(y); + const sz = sin(z); + const cz = cos(z); out.x = sx * cy * cz + cx * sy * sz; out.y = cx * sy * cz + sx * cy * sz; @@ -571,8 +584,8 @@ export class Quat extends ValueType { public static fromAngleZ (out: Out, z: number): Out { z *= halfToRad; out.x = out.y = 0; - out.z = Math.sin(z); - out.w = Math.cos(z); + out.z = sin(z); + out.w = cos(z); return out; } @@ -634,23 +647,23 @@ export class Quat extends ValueType { const test = x * y + z * w; if (test > 0.499999) { bank = 0; // default to zero - heading = toDegree(2 * Math.atan2(x, w)); + heading = toDegree(2 * atan2(x, w)); attitude = 90; } else if (test < -0.499999) { bank = 0; // default to zero - heading = -toDegree(2 * Math.atan2(x, w)); + heading = -toDegree(2 * atan2(x, w)); attitude = -90; } else { const sqx = x * x; const sqy = y * y; const sqz = z * z; - bank = toDegree(Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz)); - heading = toDegree(Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz)); - attitude = toDegree(Math.asin(2 * test)); + bank = toDegree(atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz)); + heading = toDegree(atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz)); + attitude = toDegree(asin(2 * test)); if (outerZ) { - bank = -180 * Math.sign(bank + 1e-6) + bank; - heading = -180 * Math.sign(heading + 1e-6) + heading; - attitude = 180 * Math.sign(attitude + 1e-6) - attitude; + bank = -180 * sign(bank + 1e-6) + bank; + heading = -180 * sign(heading + 1e-6) + heading; + attitude = 180 * sign(attitude + 1e-6) - attitude; } } out.x = bank; out.y = heading; out.z = attitude; @@ -709,10 +722,10 @@ export class Quat extends ValueType { * @zh 排除浮点数误差的四元数近似等价判断 */ public static equals (a: IQuatLike, b: IQuatLike, epsilon = EPSILON): boolean { - return (Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) - && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) - && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) - && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w))); + return (abs(a.x - b.x) <= epsilon * max(1.0, abs(a.x), abs(b.x)) + && abs(a.y - b.y) <= epsilon * max(1.0, abs(a.y), abs(b.y)) + && abs(a.z - b.z) <= epsilon * max(1.0, abs(a.z), abs(b.z)) + && abs(a.w - b.w) <= epsilon * max(1.0, abs(a.w), abs(b.w))); } /** @@ -723,8 +736,8 @@ export class Quat extends ValueType { * @returns Angle between the two quaternions in radians */ public static angle (a: IQuatLike, b: IQuatLike): number { - const dot = Math.min(Math.abs(Quat.dot(a, b)), 1.0); - return Math.acos(dot) * 2.0; + const dot = min(abs(Quat.dot(a, b)), 1.0); + return acos(dot) * 2.0; } /** @@ -745,7 +758,7 @@ export class Quat extends ValueType { return out; } - const t = Math.min(maxStep / toDegree(angle), 1.0); + const t = min(maxStep / toDegree(angle), 1.0); return Quat.slerp(out, from, to, t); } @@ -838,10 +851,7 @@ export class Quat extends ValueType { * @returns Returns `true' when the components of the two quaternions are equal within the specified error range; otherwise, returns `false'. */ public equals (other: Quat, epsilon = EPSILON): boolean { - return (Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) - && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) - && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) - && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w))); + return Quat.equals(this, other, epsilon); } /** @@ -870,11 +880,12 @@ export class Quat extends ValueType { * @param ratio The interpolation coefficient. The range is [0,1]. */ public lerp (to: Quat, ratio: number): Quat { - this.x += ratio * (to.x - this.x); - this.y += ratio * (to.y - this.y); - this.z += ratio * (to.z - this.z); - this.w += ratio * (to.w - this.w); - return this; + const self = this; + self.x += ratio * (to.x - self.x); + self.y += ratio * (to.y - self.y); + self.z += ratio * (to.z - self.z); + self.w += ratio * (to.w - self.w); + return self; } /** @@ -892,7 +903,9 @@ export class Quat extends ValueType { * @zh 求四元数长度 */ public length (): number { - return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + const self = this; + const { x, y, z, w } = self; + return sqrt(x * x + y * y + z * z + w * w); } /** @@ -900,7 +913,9 @@ export class Quat extends ValueType { * @zh 求四元数长度平方 */ public lengthSqr (): number { - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + const self = this; + const { x, y, z, w } = self; + return x * x + y * y + z * z + w * w; } } @@ -908,7 +923,7 @@ const qt_1 = new Quat(); const qt_2 = new Quat(); const v3_1 = new Vec3(); const m3_1 = new Mat3(); -const halfToRad = 0.5 * Math.PI / 180.0; +const halfToRad = 0.5 * PI / 180.0; CCClass.fastDefine('cc.Quat', Quat, { x: 0, y: 0, z: 0, w: 1 }); legacyCC.Quat = Quat; diff --git a/cocos/core/math/rect.ts b/cocos/core/math/rect.ts index fb15c932e09..735135a769c 100644 --- a/cocos/core/math/rect.ts +++ b/cocos/core/math/rect.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-this-alias */ /* Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. @@ -31,6 +32,9 @@ import { IRectLike, IVec2Like } from './type-define'; import { Vec2 } from './vec2'; import { legacyCC } from '../global-exports'; +const max = Math.max; +const min = Math.min; + /** * @en * A 2D rectangle defined by x, y position at the bottom-left corner and width, height. @@ -50,10 +54,10 @@ export class Rect extends ValueType { * @returns Target rectangle. */ public static fromMinMax (out: Out, v1: VecLike, v2: VecLike): Out { - const minX = Math.min(v1.x, v2.x); - const minY = Math.min(v1.y, v2.y); - const maxX = Math.max(v1.x, v2.x); - const maxY = Math.max(v1.y, v2.y); + const minX = min(v1.x, v2.x); + const minY = min(v1.y, v2.y); + const maxX = max(v1.x, v2.x); + const maxY = max(v1.y, v2.y); out.x = minX; out.y = minY; out.width = maxX - minX; @@ -99,10 +103,10 @@ export class Rect extends ValueType { const byMin = other.y; const bxMax = other.x + other.width; const byMax = other.y + other.height; - out.x = Math.max(axMin, bxMin); - out.y = Math.max(ayMin, byMin); - out.width = Math.min(axMax, bxMax) - out.x; - out.height = Math.min(ayMax, byMax) - out.y; + out.x = max(axMin, bxMin); + out.y = max(ayMin, byMin); + out.width = min(axMax, bxMax) - out.x; + out.height = min(ayMax, byMax) - out.y; return out; } @@ -123,10 +127,10 @@ export class Rect extends ValueType { const by = other.y; const bw = other.width; const bh = other.height; - out.x = Math.min(x, bx); - out.y = Math.min(y, by); - out.width = Math.max(x + w, bx + bw) - out.x; - out.height = Math.max(y + h, by + bh) - out.y; + out.x = min(x, bx); + out.y = min(y, by); + out.width = max(x + w, bx + bw) - out.x; + out.height = max(y + h, by + bh) - out.y; return out; } @@ -327,18 +331,19 @@ export class Rect extends ValueType { public set (x?: number, y?: number, width?: number, height?: number): any; public set (x?: Rect | number, y?: number, width?: number, height?: number): any { + const self = this; if (typeof x === 'object') { - this.x = x.x; - this.y = x.y; - this.width = x.width; - this.height = x.height; + self.x = x.x; + self.y = x.y; + self.width = x.width; + self.height = x.height; } else { - this.x = x || 0; - this.y = y || 0; - this.width = width || 0; - this.height = height || 0; + self.x = x || 0; + self.y = y || 0; + self.width = width || 0; + self.height = height || 0; } - return this; + return self; } /** @@ -348,10 +353,11 @@ export class Rect extends ValueType { * @returns Returns `true' when the minimum and maximum values of both rectangles are equal, respectively; otherwise, returns `false'. */ public equals (other: Rect): boolean { - return this.x === other.x - && this.y === other.y - && this.width === other.width - && this.height === other.height; + const self = this; + return self.x === other.x + && self.y === other.y + && self.width === other.width + && self.height === other.height; } /** @@ -361,16 +367,17 @@ export class Rect extends ValueType { * @param ratio The interpolation coefficient.The range is [0,1]. */ public lerp (to: Rect, ratio: number): Rect { - const x = this.x; - const y = this.y; - const w = this.width; - const h = this.height; - this.x = x + (to.x - x) * ratio; - this.y = y + (to.y - y) * ratio; - this.width = w + (to.width - w) * ratio; - this.height = h + (to.height - h) * ratio; - - return this; + const self = this; + const x = self.x; + const y = self.y; + const w = self.width; + const h = self.height; + self.x = x + (to.x - x) * ratio; + self.y = y + (to.y - y) * ratio; + self.width = w + (to.width - w) * ratio; + self.height = h + (to.height - h) * ratio; + + return self; } /** @@ -379,7 +386,8 @@ export class Rect extends ValueType { * @returns The information of the current rect in string */ public toString (): string { - return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.width.toFixed(2)}, ${this.height.toFixed(2)})`; + const self = this; + return `(${self.x.toFixed(2)}, ${self.y.toFixed(2)}, ${self.width.toFixed(2)}, ${self.height.toFixed(2)})`; } /** @@ -389,11 +397,12 @@ export class Rect extends ValueType { * @returns If intersected, return `true', otherwise return `false'. */ public intersects (other: Rect): boolean { - const maxax = this.x + this.width; - const maxay = this.y + this.height; + const self = this; + const maxax = self.x + self.width; + const maxay = self.y + self.height; const maxbx = other.x + other.width; const maxby = other.y + other.height; - return !(maxax < other.x || maxbx < this.x || maxay < other.y || maxby < this.y); + return !(maxax < other.x || maxbx < self.x || maxay < other.y || maxby < self.y); } /** @@ -403,10 +412,11 @@ export class Rect extends ValueType { * @returns The specified point is included in the rectangle and returns `true', otherwise it returns `false'. */ public contains (point: Vec2): boolean { - return (this.x <= point.x - && this.x + this.width >= point.x - && this.y <= point.y - && this.y + this.height >= point.y); + const self = this; + return (self.x <= point.x + && self.x + self.width >= point.x + && self.y <= point.y + && self.y + self.height >= point.y); } /** @@ -416,10 +426,11 @@ export class Rect extends ValueType { * @returns Returns `true' if all the points of the specified rectangle are included in the current rectangle, `false' otherwise. */ public containsRect (other: Rect): boolean { - return (this.x <= other.x - && this.x + this.width >= other.x + other.width - && this.y <= other.y - && this.y + this.height >= other.y + other.height); + const self = this; + return (self.x <= other.x + && self.x + self.width >= other.x + other.width + && self.y <= other.y + && self.y + self.height >= other.y + other.height); } /** @@ -432,10 +443,11 @@ export class Rect extends ValueType { * @param matrix The matrix4 */ public transformMat4 (mat: Mat4): Rect { - const ol = this.x; - const ob = this.y; - const or = ol + this.width; - const ot = ob + this.height; + const self = this; + const ol = self.x; + const ob = self.y; + const or = ol + self.width; + const ot = ob + self.height; const lbx = mat.m00 * ol + mat.m04 * ob + mat.m12; const lby = mat.m01 * ol + mat.m05 * ob + mat.m13; const rbx = mat.m00 * or + mat.m04 * ob + mat.m12; @@ -445,17 +457,17 @@ export class Rect extends ValueType { const rtx = mat.m00 * or + mat.m04 * ot + mat.m12; const rty = mat.m01 * or + mat.m05 * ot + mat.m13; - const minX = Math.min(lbx, rbx, ltx, rtx); - const maxX = Math.max(lbx, rbx, ltx, rtx); - const minY = Math.min(lby, rby, lty, rty); - const maxY = Math.max(lby, rby, lty, rty); + const minX = min(lbx, rbx, ltx, rtx); + const maxX = max(lbx, rbx, ltx, rtx); + const minY = min(lby, rby, lty, rty); + const maxY = max(lby, rby, lty, rty); - this.x = minX; - this.y = minY; - this.width = maxX - minX; - this.height = maxY - minY; + self.x = minX; + self.y = minY; + self.width = maxX - minX; + self.height = maxY - minY; - return this; + return self; } /** @@ -471,10 +483,11 @@ export class Rect extends ValueType { * @param out_rt The right top point */ public transformMat4ToPoints (mat: Mat4, out_lb: Vec2, out_lt: Vec2, out_rt: Vec2, out_rb: Vec2): void { - const ol = this.x; - const ob = this.y; - const or = ol + this.width; - const ot = ob + this.height; + const self = this; + const ol = self.x; + const ob = self.y; + const or = ol + self.width; + const ot = ob + self.height; out_lb.x = mat.m00 * ol + mat.m04 * ob + mat.m12; out_lb.y = mat.m01 * ol + mat.m05 * ob + mat.m13; out_rb.x = mat.m00 * or + mat.m04 * ob + mat.m12; diff --git a/cocos/core/math/vec2.ts b/cocos/core/math/vec2.ts index 9f80a0bd17f..b36576e48c9 100644 --- a/cocos/core/math/vec2.ts +++ b/cocos/core/math/vec2.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-this-alias */ /* Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. @@ -33,6 +34,19 @@ import { Vec3 } from './vec3'; import { legacyCC } from '../global-exports'; import { warnID } from '../platform/debug'; +const abs = Math.abs; +const max = Math.max; +const min = Math.min; +const PI = Math.PI; +const acos = Math.acos; +const sin = Math.sin; +const cos = Math.cos; +const sqrt = Math.sqrt; +const atan2 = Math.atan2; +const ceil = Math.ceil; +const floor = Math.floor; +const round = Math.round; + /** * @en Representation of 2D vectors and points. * @zh 二维向量。 @@ -117,8 +131,8 @@ export class Vec2 extends ValueType { * @zh 逐元素向量向上取整 */ public static ceil (out: Out, a: Out): Out { - out.x = Math.ceil(a.x); - out.y = Math.ceil(a.y); + out.x = ceil(a.x); + out.y = ceil(a.y); return out; } @@ -127,8 +141,8 @@ export class Vec2 extends ValueType { * @zh 逐元素向量向下取整 */ public static floor (out: Out, a: Out): Out { - out.x = Math.floor(a.x); - out.y = Math.floor(a.y); + out.x = floor(a.x); + out.y = floor(a.y); return out; } @@ -137,8 +151,8 @@ export class Vec2 extends ValueType { * @zh 逐元素向量最小值 */ public static min (out: Out, a: Out, b: Out): Out { - out.x = Math.min(a.x, b.x); - out.y = Math.min(a.y, b.y); + out.x = min(a.x, b.x); + out.y = min(a.y, b.y); return out; } @@ -147,8 +161,8 @@ export class Vec2 extends ValueType { * @zh 逐元素向量最大值 */ public static max (out: Out, a: Out, b: Out): Out { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); + out.x = max(a.x, b.x); + out.y = max(a.y, b.y); return out; } @@ -157,8 +171,8 @@ export class Vec2 extends ValueType { * @zh 逐元素向量四舍五入取整 */ public static round (out: Out, a: Out): Out { - out.x = Math.round(a.x); - out.y = Math.round(a.y); + out.x = round(a.x); + out.y = round(a.y); return out; } @@ -189,7 +203,7 @@ export class Vec2 extends ValueType { public static distance (a: Out, b: Out): number { const x = b.x - a.x; const y = b.y - a.y; - return Math.sqrt(x * x + y * y); + return sqrt(x * x + y * y); } /** @@ -209,7 +223,7 @@ export class Vec2 extends ValueType { public static len (a: Out): number { const x = a.x; const y = a.y; - return Math.sqrt(x * x + y * y); + return sqrt(x * x + y * y); } /** @@ -250,13 +264,13 @@ export class Vec2 extends ValueType { const x = a.x; const y = a.y; - if (Math.abs(x) < EPSILON) { + if (abs(x) < EPSILON) { out.x = 0; } else { out.x = 1.0 / x; } - if (Math.abs(y) < EPSILON) { + if (abs(y) < EPSILON) { out.y = 0; } else { out.y = 1.0 / y; @@ -274,7 +288,7 @@ export class Vec2 extends ValueType { const y = a.y; let len = x * x + y * y; if (len > 0) { - len = 1 / Math.sqrt(len); + len = 1 / sqrt(len); out.x = x * len; out.y = y * len; } else { @@ -334,9 +348,9 @@ export class Vec2 extends ValueType { */ public static random (out: Out, scale?: number): Out { scale = scale || 1.0; - const r = random() * 2.0 * Math.PI; - out.x = Math.cos(r) * scale; - out.y = Math.sin(r) * scale; + const r = random() * 2.0 * PI; + out.x = cos(r) * scale; + out.y = sin(r) * scale; return out; } @@ -408,10 +422,8 @@ export class Vec2 extends ValueType { */ public static equals (a: Out, b: Out, epsilon = EPSILON): boolean { return ( - Math.abs(a.x - b.x) - <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) - && Math.abs(a.y - b.y) - <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) + abs(a.x - b.x) <= epsilon * max(1.0, abs(a.x), abs(b.x)) + && abs(a.y - b.y) <= epsilon * max(1.0, abs(a.y), abs(b.y)) ); } @@ -428,9 +440,9 @@ export class Vec2 extends ValueType { } const dot = a.x * b.x + a.y * b.y; - let cosine = dot / (Math.sqrt(magSqr1 * magSqr2)); + let cosine = dot / (sqrt(magSqr1 * magSqr2)); cosine = clamp(cosine, -1.0, 1.0); - return Math.acos(cosine); + return acos(cosine); } /** @@ -504,12 +516,7 @@ export class Vec2 extends ValueType { * @return Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ public equals (other: Vec2, epsilon = EPSILON): boolean { - return ( - Math.abs(this.x - other.x) - <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) - && Math.abs(this.y - other.y) - <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) - ); + return Vec2.equals(this, other, epsilon); } /** @@ -522,10 +529,8 @@ export class Vec2 extends ValueType { */ public equals2f (x: number, y: number, epsilon = EPSILON): boolean { return ( - Math.abs(this.x - x) - <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) - && Math.abs(this.y - y) - <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y)) + abs(this.x - x) <= epsilon * max(1.0, abs(this.x), abs(x)) + && abs(this.y - y) <= epsilon * max(1.0, abs(this.y), abs(y)) ); } @@ -731,7 +736,7 @@ export class Vec2 extends ValueType { * @return Length of vector */ public length (): number { - return Math.sqrt(this.x * this.x + this.y * this.y); + return sqrt(this.x * this.x + this.y * this.y); } /** @@ -748,15 +753,16 @@ export class Vec2 extends ValueType { * @zh 将当前向量归一化。 */ public normalize (): Vec2 { - const x = this.x; - const y = this.y; + const self = this; + const x = self.x; + const y = self.y; let len = x * x + y * y; if (len > 0) { - len = 1 / Math.sqrt(len); - this.x *= len; - this.y *= len; + len = 1 / sqrt(len); + self.x *= len; + self.y *= len; } - return this; + return self; } /** @@ -774,9 +780,9 @@ export class Vec2 extends ValueType { } const dot = this.dot(other); - let cosine = dot / (Math.sqrt(magSqr1 * magSqr2)); + let cosine = dot / (sqrt(magSqr1 * magSqr2)); cosine = clamp(cosine, -1.0, 1.0); - return Math.acos(cosine); + return acos(cosine); } /** @@ -795,7 +801,7 @@ export class Vec2 extends ValueType { // = atan2(cross(a, b), dot(a, b)) const cross = this.cross(other); const dot = this.dot(other); - return Math.atan2(cross, dot); + return atan2(cross, dot); } /** @@ -807,10 +813,10 @@ export class Vec2 extends ValueType { const x = this.x; const y = this.y; - const sin = Math.sin(radians); - const cos = Math.cos(radians); - this.x = cos * x - sin * y; - this.y = sin * x + cos * y; + const s = sin(radians); + const c = cos(radians); + this.x = c * x - s * y; + this.y = s * x + c * y; return this; } diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index 693ac30d662..8533bede8b8 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-this-alias */ /* Copyright (c) 2016 Chukong Technologies Inc. Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. @@ -32,6 +33,18 @@ import { clamp, EPSILON, lerp, random } from './utils'; import { legacyCC } from '../global-exports'; import { warnID } from '../platform/debug'; +const abs = Math.abs; +const max = Math.max; +const min = Math.min; +const PI = Math.PI; +const acos = Math.acos; +const sin = Math.sin; +const cos = Math.cos; +const sqrt = Math.sqrt; +const ceil = Math.ceil; +const floor = Math.floor; +const round = Math.round; + /** * @en Representation of 3D vectors and points. * @zh 三维向量。 @@ -137,9 +150,9 @@ export class Vec3 extends ValueType { * @zh 逐元素向量向上取整 */ public static ceil (out: Out, a: IVec3Like): Out { - out.x = Math.ceil(a.x); - out.y = Math.ceil(a.y); - out.z = Math.ceil(a.z); + out.x = ceil(a.x); + out.y = ceil(a.y); + out.z = ceil(a.z); return out; } @@ -148,9 +161,9 @@ export class Vec3 extends ValueType { * @zh 逐元素向量向下取整 */ public static floor (out: Out, a: IVec3Like): Out { - out.x = Math.floor(a.x); - out.y = Math.floor(a.y); - out.z = Math.floor(a.z); + out.x = floor(a.x); + out.y = floor(a.y); + out.z = floor(a.z); return out; } @@ -159,9 +172,9 @@ export class Vec3 extends ValueType { * @zh 逐元素向量最小值 */ public static min (out: Out, a: IVec3Like, b: IVec3Like): Out { - out.x = Math.min(a.x, b.x); - out.y = Math.min(a.y, b.y); - out.z = Math.min(a.z, b.z); + out.x = min(a.x, b.x); + out.y = min(a.y, b.y); + out.z = min(a.z, b.z); return out; } @@ -170,9 +183,9 @@ export class Vec3 extends ValueType { * @zh 逐元素向量最大值 */ public static max (out: Out, a: IVec3Like, b: IVec3Like): Out { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - out.z = Math.max(a.z, b.z); + out.x = max(a.x, b.x); + out.y = max(a.y, b.y); + out.z = max(a.z, b.z); return out; } @@ -181,9 +194,9 @@ export class Vec3 extends ValueType { * @zh 逐元素向量四舍五入取整 */ public static round (out: Out, a: IVec3Like): Out { - out.x = Math.round(a.x); - out.y = Math.round(a.y); - out.z = Math.round(a.z); + out.x = round(a.x); + out.y = round(a.y); + out.z = round(a.z); return out; } @@ -217,7 +230,7 @@ export class Vec3 extends ValueType { const x = b.x - a.x; const y = b.y - a.y; const z = b.z - a.z; - return Math.sqrt(x * x + y * y + z * z); + return sqrt(x * x + y * y + z * z); } /** @@ -239,7 +252,7 @@ export class Vec3 extends ValueType { const x = a.x; const y = a.y; const z = a.z; - return Math.sqrt(x * x + y * y + z * z); + return sqrt(x * x + y * y + z * z); } /** @@ -284,19 +297,19 @@ export class Vec3 extends ValueType { const y = a.y; const z = a.z; - if (Math.abs(x) < EPSILON) { + if (abs(x) < EPSILON) { out.x = 0; } else { out.x = 1.0 / x; } - if (Math.abs(y) < EPSILON) { + if (abs(y) < EPSILON) { out.y = 0; } else { out.y = 1.0 / y; } - if (Math.abs(z) < EPSILON) { + if (abs(z) < EPSILON) { out.z = 0; } else { out.z = 1.0 / z; @@ -316,7 +329,7 @@ export class Vec3 extends ValueType { let len = x * x + y * y + z * z; if (len > 0) { - len = 1 / Math.sqrt(len); + len = 1 / sqrt(len); out.x = x * len; out.y = y * len; out.z = z * len; @@ -411,20 +424,20 @@ export class Vec3 extends ValueType { // every vector that orthonormal to the directions can be the rotation axis. const fromNormalized = Vec3.multiplyScalar(cacheV1, from, 1.0 / lenFrom); const axis = Vec3.generateOrthogonal(cacheV2, fromNormalized); - const angle = Math.PI * t; + const angle = PI * t; rotateAxisAngle(cacheV3, fromNormalized, axis, angle); Vec3.multiplyScalar(out, cacheV3, lenLerped); return out; } else { // Do not have to clamp. We done it before. const dotClamped = dot; - const theta = Math.acos(dotClamped) * t; + const theta = acos(dotClamped) * t; const fromNormalized = Vec3.multiplyScalar(cacheV1, from, 1.0 / lenFrom); const toNormalized = Vec3.multiplyScalar(cacheV2, to, 1.0 / lenTo); Vec3.scaleAndAdd(cacheV3, toNormalized, fromNormalized, -dotClamped); Vec3.normalize(cacheV3, cacheV3); - Vec3.multiplyScalar(cacheV3, cacheV3, Math.sin(theta)); - Vec3.scaleAndAdd(cacheV3, cacheV3, fromNormalized, Math.cos(theta)); + Vec3.multiplyScalar(cacheV3, cacheV3, sin(theta)); + Vec3.scaleAndAdd(cacheV3, cacheV3, fromNormalized, cos(theta)); Vec3.multiplyScalar(out, cacheV3, lenLerped); return out; } @@ -439,12 +452,12 @@ export class Vec3 extends ValueType { public static random (out: Out, scale?: number): Out { scale = scale || 1.0; - const phi = random() * 2.0 * Math.PI; + const phi = random() * 2.0 * PI; const cosTheta = random() * 2 - 1; - const sinTheta = Math.sqrt(1 - cosTheta * cosTheta); + const sinTheta = sqrt(1 - cosTheta * cosTheta); - out.x = sinTheta * Math.cos(phi) * scale; - out.y = sinTheta * Math.sin(phi) * scale; + out.x = sinTheta * cos(phi) * scale; + out.y = sinTheta * sin(phi) * scale; out.z = cosTheta * scale; return out; } @@ -579,11 +592,11 @@ export class Vec3 extends ValueType { const z = v.z - o.z; // perform rotation - const cos = Math.cos(a); - const sin = Math.sin(a); + const c = cos(a); + const s = sin(a); const rx = x; - const ry = y * cos - z * sin; - const rz = y * sin + z * cos; + const ry = y * c - z * s; + const rz = y * s + z * c; // translate to correct position out.x = rx + o.x; @@ -607,11 +620,11 @@ export class Vec3 extends ValueType { const z = v.z - o.z; // perform rotation - const cos = Math.cos(a); - const sin = Math.sin(a); - const rx = z * sin + x * cos; + const c = cos(a); + const s = sin(a); + const rx = z * s + x * c; const ry = y; - const rz = z * cos - x * sin; + const rz = z * c - x * s; // translate to correct position out.x = rx + o.x; @@ -635,10 +648,10 @@ export class Vec3 extends ValueType { const z = v.z - o.z; // perform rotation - const cos = Math.cos(a); - const sin = Math.sin(a); - const rx = x * cos - y * sin; - const ry = x * sin + y * cos; + const c = cos(a); + const s = sin(a); + const rx = x * c - y * s; + const ry = x * s + y * c; const rz = z; // translate to correct position @@ -668,11 +681,11 @@ export class Vec3 extends ValueType { const ny = n.y; const nz = n.z; - const cos = Math.cos(a); - const sin = Math.sin(a); - const rx = x * (nx * nx * (1.0 - cos) + cos) + y * (nx * ny * (1.0 - cos) - nz * sin) + z * (nx * nz * (1.0 - cos) + ny * sin); - const ry = x * (nx * ny * (1.0 - cos) + nz * sin) + y * (ny * ny * (1.0 - cos) + cos) + z * (ny * nz * (1.0 - cos) - nx * sin); - const rz = x * (nx * nz * (1.0 - cos) - ny * sin) + y * (ny * nz * (1.0 - cos) + nx * sin) + z * (nz * nz * (1.0 - cos) + cos); + const c = cos(a); + const s = sin(a); + const rx = x * (nx * nx * (1.0 - c) + c) + y * (nx * ny * (1.0 - c) - nz * s) + z * (nx * nz * (1.0 - c) + ny * s); + const ry = x * (nx * ny * (1.0 - c) + nz * s) + y * (ny * ny * (1.0 - c) + c) + z * (ny * nz * (1.0 - c) - nx * s); + const rz = x * (nx * nz * (1.0 - c) - ny * s) + y * (ny * nz * (1.0 - c) + nx * s) + z * (nz * nz * (1.0 - c) + c); // translate to correct position out.x = rx + o.x; @@ -723,12 +736,9 @@ export class Vec3 extends ValueType { const { x: a0, y: a1, z: a2 } = a; const { x: b0, y: b1, z: b2 } = b; return ( - Math.abs(a0 - b0) - <= epsilon * Math.max(1.0, Math.abs(a0), Math.abs(b0)) - && Math.abs(a1 - b1) - <= epsilon * Math.max(1.0, Math.abs(a1), Math.abs(b1)) - && Math.abs(a2 - b2) - <= epsilon * Math.max(1.0, Math.abs(a2), Math.abs(b2)) + abs(a0 - b0) <= epsilon * max(1.0, abs(a0), abs(b0)) + && abs(a1 - b1) <= epsilon * max(1.0, abs(a1), abs(b1)) + && abs(a2 - b2) <= epsilon * max(1.0, abs(a2), abs(b2)) ); } @@ -745,9 +755,9 @@ export class Vec3 extends ValueType { } const dot = a.x * b.x + a.y * b.y + a.z * b.z; - let cosine = dot / (Math.sqrt(magSqr1 * magSqr2)); + let cosine = dot / (sqrt(magSqr1 * magSqr2)); cosine = clamp(cosine, -1.0, 1.0); - return Math.acos(cosine); + return acos(cosine); } /** @@ -829,7 +839,7 @@ export class Vec3 extends ValueType { return out; } - const distance = Math.sqrt(distanceSqr); + const distance = sqrt(distanceSqr); const scale = maxStep / distance; out.x = current.x + deltaX * scale; out.y = current.y + deltaY * scale; @@ -850,9 +860,9 @@ export class Vec3 extends ValueType { // 1. Drop the component with minimal magnitude. // 2. Negate one of the remain components. // 3. Swap the remain components. - const absX = Math.abs(x); - const absY = Math.abs(y); - const absZ = Math.abs(z); + const absX = abs(x); + const absY = abs(y); + const absZ = abs(z); if (absX < absY && absX < absZ) { Vec3.set(out, 0.0, z, -y); } else if (absY < absZ) { @@ -945,11 +955,7 @@ export class Vec3 extends ValueType { * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ public equals (other: Vec3, epsilon = EPSILON): boolean { - return ( - Math.abs(this.x - other.x) <= epsilon - && Math.abs(this.y - other.y) <= epsilon - && Math.abs(this.z - other.z) <= epsilon - ); + return Vec3.equals(this, other, epsilon); } /** @@ -963,9 +969,9 @@ export class Vec3 extends ValueType { */ public equals3f (x: number, y: number, z: number, epsilon = EPSILON): boolean { return ( - Math.abs(this.x - x) <= epsilon - && Math.abs(this.y - y) <= epsilon - && Math.abs(this.z - z) <= epsilon + abs(this.x - x) <= epsilon + && abs(this.y - y) <= epsilon + && abs(this.z - z) <= epsilon ); } @@ -1191,7 +1197,8 @@ export class Vec3 extends ValueType { * @returns Length of vector */ public length (): number { - return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + const self = this; + return sqrt(self.x * self.x + self.y * self.y + self.z * self.z); } /** @@ -1200,7 +1207,8 @@ export class Vec3 extends ValueType { * @returns the squared length of this vector */ public lengthSqr (): number { - return this.x * this.x + this.y * this.y + this.z * this.z; + const self = this; + return self.x * self.x + self.y * self.y + self.z * self.z; } /** @@ -1208,19 +1216,20 @@ export class Vec3 extends ValueType { * @zh 将当前向量归一化 */ public normalize (): Vec3 { - const x = this.x; - const y = this.y; - const z = this.z; + const self = this; + const x = self.x; + const y = self.y; + const z = self.z; let len = x * x + y * y + z * z; if (len > 0) { - len = 1 / Math.sqrt(len); - this.x = x * len; - this.y = y * len; - this.z = z * len; + len = 1 / sqrt(len); + self.x = x * len; + self.y = y * len; + self.z = z * len; } - return this; + return self; } /** @@ -1229,15 +1238,16 @@ export class Vec3 extends ValueType { * @param matrix matrix to transform with */ public transformMat4 (matrix: Mat4): Vec3 { - const x = this.x; - const y = this.y; - const z = this.z; + const self = this; + const x = self.x; + const y = self.y; + const z = self.z; let rhw = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15; rhw = rhw ? 1 / rhw : 1; - this.x = (matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12) * rhw; - this.y = (matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13) * rhw; - this.z = (matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14) * rhw; - return this; + self.x = (matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12) * rhw; + self.y = (matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13) * rhw; + self.z = (matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14) * rhw; + return self; } /** @@ -1273,11 +1283,11 @@ const rotateAxisAngle = ((): (out: Vec3, input: Readonly, axis: Readonly (out: Out, a: Out): Out { - out.x = Math.ceil(a.x); - out.y = Math.ceil(a.y); - out.z = Math.ceil(a.z); - out.w = Math.ceil(a.w); + out.x = ceil(a.x); + out.y = ceil(a.y); + out.z = ceil(a.z); + out.w = ceil(a.w); return out; } @@ -169,10 +181,10 @@ export class Vec4 extends ValueType { * @zh 逐元素向量向下取整 */ public static floor (out: Out, a: Out): Out { - out.x = Math.floor(a.x); - out.y = Math.floor(a.y); - out.z = Math.floor(a.z); - out.w = Math.floor(a.w); + out.x = floor(a.x); + out.y = floor(a.y); + out.z = floor(a.z); + out.w = floor(a.w); return out; } @@ -181,10 +193,10 @@ export class Vec4 extends ValueType { * @zh 逐元素向量最小值 */ public static min (out: Out, a: Out, b: Out): Out { - out.x = Math.min(a.x, b.x); - out.y = Math.min(a.y, b.y); - out.z = Math.min(a.z, b.z); - out.w = Math.min(a.w, b.w); + out.x = min(a.x, b.x); + out.y = min(a.y, b.y); + out.z = min(a.z, b.z); + out.w = min(a.w, b.w); return out; } @@ -193,10 +205,10 @@ export class Vec4 extends ValueType { * @zh 逐元素向量最大值 */ public static max (out: Out, a: Out, b: Out): Out { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - out.z = Math.max(a.z, b.z); - out.w = Math.max(a.w, b.w); + out.x = max(a.x, b.x); + out.y = max(a.y, b.y); + out.z = max(a.z, b.z); + out.w = max(a.w, b.w); return out; } @@ -205,10 +217,10 @@ export class Vec4 extends ValueType { * @zh 逐元素向量四舍五入取整 */ public static round (out: Out, a: Out): Out { - out.x = Math.round(a.x); - out.y = Math.round(a.y); - out.z = Math.round(a.z); - out.w = Math.round(a.w); + out.x = round(a.x); + out.y = round(a.y); + out.z = round(a.z); + out.w = round(a.w); return out; } @@ -245,7 +257,7 @@ export class Vec4 extends ValueType { const y = b.y - a.y; const z = b.z - a.z; const w = b.w - a.w; - return Math.sqrt(x * x + y * y + z * z + w * w); + return sqrt(x * x + y * y + z * z + w * w); } /** @@ -269,7 +281,7 @@ export class Vec4 extends ValueType { const y = a.y; const z = a.z; const w = a.w; - return Math.sqrt(x * x + y * y + z * z + w * w); + return sqrt(x * x + y * y + z * z + w * w); } /** @@ -318,25 +330,25 @@ export class Vec4 extends ValueType { const z = a.z; const w = a.w; - if (Math.abs(x) < EPSILON) { + if (abs(x) < EPSILON) { out.x = 0; } else { out.x = 1.0 / x; } - if (Math.abs(y) < EPSILON) { + if (abs(y) < EPSILON) { out.y = 0; } else { out.y = 1.0 / y; } - if (Math.abs(z) < EPSILON) { + if (abs(z) < EPSILON) { out.z = 0; } else { out.z = 1.0 / z; } - if (Math.abs(w) < EPSILON) { + if (abs(w) < EPSILON) { out.w = 0; } else { out.w = 1.0 / w; @@ -356,7 +368,7 @@ export class Vec4 extends ValueType { const w = a.w; let len = x * x + y * y + z * z + w * w; if (len > 0) { - len = 1 / Math.sqrt(len); + len = 1 / sqrt(len); out.x = x * len; out.y = y * len; out.z = z * len; @@ -410,12 +422,12 @@ export class Vec4 extends ValueType { public static random (out: Out, scale?: number): Out { scale = scale || 1.0; - const phi = random() * 2.0 * Math.PI; + const phi = random() * 2.0 * PI; const cosTheta = random() * 2 - 1; - const sinTheta = Math.sqrt(1 - cosTheta * cosTheta); + const sinTheta = sqrt(1 - cosTheta * cosTheta); - out.x = sinTheta * Math.cos(phi) * scale; - out.y = sinTheta * Math.sin(phi) * scale; + out.x = sinTheta * cos(phi) * scale; + out.y = sinTheta * sin(phi) * scale; out.z = cosTheta * scale; out.w = 0; return out; @@ -522,12 +534,19 @@ export class Vec4 extends ValueType { public static equals (a: Out, b: Out, epsilon = EPSILON): boolean { // relative epsilon comparison with small number guard: // https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ - const hasInf = Math.abs(a.x) === Infinity || Math.abs(a.y) === Infinity || Math.abs(a.z) === Infinity || Math.abs(a.w) === Infinity - || Math.abs(b.x) === Infinity || Math.abs(b.y) === Infinity || Math.abs(b.z) === Infinity || Math.abs(b.w) === Infinity; - return !hasInf && (Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) - && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) - && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) - && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w))); + const inf = Infinity; + const hasInf = abs(a.x) === inf + || abs(a.y) === inf + || abs(a.z) === inf + || abs(a.w) === inf + || abs(b.x) === inf + || abs(b.y) === inf + || abs(b.z) === inf + || abs(b.w) === inf; + return !hasInf && (abs(a.x - b.x) <= epsilon * max(1.0, abs(a.x), abs(b.x)) + && abs(a.y - b.y) <= epsilon * max(1.0, abs(a.y), abs(b.y)) + && abs(a.z - b.z) <= epsilon * max(1.0, abs(a.z), abs(b.z)) + && abs(a.w - b.w) <= epsilon * max(1.0, abs(a.w), abs(b.w))); } /** @@ -623,10 +642,11 @@ export class Vec4 extends ValueType { * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ public equals (other: Vec4, epsilon = EPSILON): boolean { - return (Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) - && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) - && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) - && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w))); + const self = this; + return (abs(self.x - other.x) <= epsilon * max(1.0, abs(self.x), abs(other.x)) + && abs(self.y - other.y) <= epsilon * max(1.0, abs(self.y), abs(other.y)) + && abs(self.z - other.z) <= epsilon * max(1.0, abs(self.z), abs(other.z)) + && abs(self.w - other.w) <= epsilon * max(1.0, abs(self.w), abs(other.w))); } /** @@ -640,10 +660,11 @@ export class Vec4 extends ValueType { * @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`. */ public equals4f (x: number, y: number, z: number, w: number, epsilon = EPSILON): boolean { - return (Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) - && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y)) - && Math.abs(this.z - z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(z)) - && Math.abs(this.w - w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(w))); + const self = this; + return (abs(self.x - x) <= epsilon * max(1.0, abs(self.x), abs(x)) + && abs(self.y - y) <= epsilon * max(1.0, abs(self.y), abs(y)) + && abs(self.z - z) <= epsilon * max(1.0, abs(self.z), abs(z)) + && abs(self.w - w) <= epsilon * max(1.0, abs(self.w), abs(w))); } /** @@ -676,15 +697,16 @@ export class Vec4 extends ValueType { * @param ratio The interpolation coefficient.The range is [0,1]. */ public lerp (to: Vec4, ratio: number): Vec4 { - const x = this.x; - const y = this.y; - const z = this.z; - const w = this.w; - this.x = x + ratio * (to.x - x); - this.y = y + ratio * (to.y - y); - this.z = z + ratio * (to.z - z); - this.w = w + ratio * (to.w - w); - return this; + const self = this; + const x = self.x; + const y = self.y; + const z = self.z; + const w = self.w; + self.x = x + ratio * (to.x - x); + self.y = y + ratio * (to.y - y); + self.z = z + ratio * (to.z - z); + self.w = w + ratio * (to.w - w); + return self; } /** @@ -704,11 +726,12 @@ export class Vec4 extends ValueType { * @returns `this` */ public clampf (minInclusive: Vec4, maxInclusive: Vec4): Vec4 { - this.x = clamp(this.x, minInclusive.x, maxInclusive.x); - this.y = clamp(this.y, minInclusive.y, maxInclusive.y); - this.z = clamp(this.z, minInclusive.z, maxInclusive.z); - this.w = clamp(this.w, minInclusive.w, maxInclusive.w); - return this; + const self = this; + self.x = clamp(self.x, minInclusive.x, maxInclusive.x); + self.y = clamp(self.y, minInclusive.y, maxInclusive.y); + self.z = clamp(self.z, minInclusive.z, maxInclusive.z); + self.w = clamp(self.w, minInclusive.w, maxInclusive.w); + return self; } /** @@ -717,11 +740,12 @@ export class Vec4 extends ValueType { * @param other specified vector */ public add (other: Vec4): Vec4 { - this.x += other.x; - this.y += other.y; - this.z += other.z; - this.w += other.w; - return this; + const self = this; + self.x += other.x; + self.y += other.y; + self.z += other.z; + self.w += other.w; + return self; } /** @@ -733,11 +757,12 @@ export class Vec4 extends ValueType { * @param w The w value of specified vector */ public add4f (x: number, y: number, z: number, w: number): Vec4 { - this.x += x; - this.y += y; - this.z += z; - this.w += w; - return this; + const self = this; + self.x += x; + self.y += y; + self.z += z; + self.w += w; + return self; } /** @@ -746,11 +771,12 @@ export class Vec4 extends ValueType { * @param other specified vector */ public subtract (other: Vec4): Vec4 { - this.x -= other.x; - this.y -= other.y; - this.z -= other.z; - this.w -= other.w; - return this; + const self = this; + self.x -= other.x; + self.y -= other.y; + self.z -= other.z; + self.w -= other.w; + return self; } /** @@ -762,11 +788,12 @@ export class Vec4 extends ValueType { * @param w The w value of specified vector */ public subtract4f (x: number, y: number, z: number, w: number): Vec4 { - this.x -= x; - this.y -= y; - this.z -= z; - this.w -= w; - return this; + const self = this; + self.x -= x; + self.y -= y; + self.z -= z; + self.w -= w; + return self; } /** @@ -775,14 +802,12 @@ export class Vec4 extends ValueType { * @param scalar scalar number */ public multiplyScalar (scalar: number): Vec4 { - if (typeof scalar === 'object') { - warnID(16361); - } - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; - return this; + const self = this; + self.x *= scalar; + self.y *= scalar; + self.z *= scalar; + self.w *= scalar; + return self; } /** @@ -791,14 +816,12 @@ export class Vec4 extends ValueType { * @param other specified vector */ public multiply (other: Vec4): Vec4 { - if (typeof other !== 'object') { - warnID(16362); - } - this.x *= other.x; - this.y *= other.y; - this.z *= other.z; - this.w *= other.w; - return this; + const self = this; + self.x *= other.x; + self.y *= other.y; + self.z *= other.z; + self.w *= other.w; + return self; } /** @@ -810,11 +833,12 @@ export class Vec4 extends ValueType { * @param w The w value of specified vector */ public multiply4f (x: number, y: number, z: number, w: number): Vec4 { - this.x *= x; - this.y *= y; - this.z *= z; - this.w *= w; - return this; + const self = this; + self.x *= x; + self.y *= y; + self.z *= z; + self.w *= w; + return self; } /** @@ -823,11 +847,12 @@ export class Vec4 extends ValueType { * @param other specified vector */ public divide (other: Vec4): Vec4 { - this.x /= other.x; - this.y /= other.y; - this.z /= other.z; - this.w /= other.w; - return this; + const self = this; + self.x /= other.x; + self.y /= other.y; + self.z /= other.z; + self.w /= other.w; + return self; } /** @@ -839,11 +864,12 @@ export class Vec4 extends ValueType { * @param w The w value of specified vector */ public divide4f (x: number, y: number, z: number, w: number): Vec4 { - this.x /= x; - this.y /= y; - this.z /= z; - this.w /= w; - return this; + const self = this; + self.x /= x; + self.y /= y; + self.z /= z; + self.w /= w; + return self; } /** @@ -851,11 +877,12 @@ export class Vec4 extends ValueType { * @zh 将当前向量的各个分量取反 */ public negative (): Vec4 { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - this.w = -this.w; - return this; + const self = this; + self.x = -self.x; + self.y = -self.y; + self.z = -self.z; + self.w = -self.w; + return self; } /** @@ -865,7 +892,8 @@ export class Vec4 extends ValueType { * @returns 当前向量与指定向量点乘的结果。 */ public dot (vector: Vec4): number { - return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w; + const self = this; + return self.x * vector.x + self.y * vector.y + self.z * vector.z + self.w * vector.w; } /** @@ -876,13 +904,14 @@ export class Vec4 extends ValueType { * @deprecated since v3.8 cross product only defined in 3D space, use [[Vec3.cross]] instead. */ public cross (vector: Vec4): Vec4 { - const { x: ax, y: ay, z: az } = this; + const self = this; + const { x: ax, y: ay, z: az } = self; const { x: bx, y: by, z: bz } = vector; - this.x = ay * bz - az * by; - this.y = az * bx - ax * bz; - this.z = ax * by - ay * bx; - return this; + self.x = ay * bz - az * by; + self.y = az * bx - ax * bz; + self.z = ax * by - ay * bx; + return self; } /** @@ -891,11 +920,12 @@ export class Vec4 extends ValueType { * @returns Length of vector */ public length (): number { - const x = this.x; - const y = this.y; - const z = this.z; - const w = this.w; - return Math.sqrt(x * x + y * y + z * z + w * w); + const self = this; + const x = self.x; + const y = self.y; + const z = self.z; + const w = self.w; + return sqrt(x * x + y * y + z * z + w * w); } /** @@ -904,10 +934,11 @@ export class Vec4 extends ValueType { * @returns the squared length of this vector */ public lengthSqr (): number { - const x = this.x; - const y = this.y; - const z = this.z; - const w = this.w; + const self = this; + const x = self.x; + const y = self.y; + const z = self.z; + const w = self.w; return x * x + y * y + z * z + w * w; } @@ -916,19 +947,20 @@ export class Vec4 extends ValueType { * @zh 将当前向量归一化 */ public normalize (): Vec4 { - const x = this.x; - const y = this.y; - const z = this.z; - const w = this.w; + const self = this; + const x = self.x; + const y = self.y; + const z = self.z; + const w = self.w; let len = x * x + y * y + z * z + w * w; if (len > 0) { - len = 1 / Math.sqrt(len); - this.x = x * len; - this.y = y * len; - this.z = z * len; - this.w = w * len; + len = 1 / sqrt(len); + self.x = x * len; + self.y = y * len; + self.z = z * len; + self.w = w * len; } - return this; + return self; } /** @@ -936,11 +968,12 @@ export class Vec4 extends ValueType { * @zh 向量数乘。 */ public scale (scalar: number): Vec4 { - this.x *= scalar; - this.y *= scalar; - this.z *= scalar; - this.w *= scalar; - return this; + const self = this; + self.x *= scalar; + self.y *= scalar; + self.z *= scalar; + self.w *= scalar; + return self; } /** @@ -949,15 +982,16 @@ export class Vec4 extends ValueType { * @param matrix matrix to transform with */ public transformMat4 (matrix: Mat4): Vec4 { - const x = this.x; - const y = this.y; - const z = this.z; - const w = this.w; - this.x = matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12 * w; - this.y = matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13 * w; - this.z = matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14 * w; - this.w = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15 * w; - return this; + const self = this; + const x = self.x; + const y = self.y; + const z = self.z; + const w = self.w; + self.x = matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12 * w; + self.y = matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13 * w; + self.z = matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14 * w; + self.w = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15 * w; + return self; } } diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index 80457ba76f6..f66b3bc5a87 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -49,8 +49,8 @@ export class CachedArray extends ScalableContainer { */ public length = 0; - private declare _compareFn?: (a: T, b: T) => number; - private _initSize = 0; + private declare _compareFn$?: (a: T, b: T) => number; + private _initSize$ = 0; /** * @en Constructor. @zh 构造函数。 @@ -64,8 +64,8 @@ export class CachedArray extends ScalableContainer { constructor (length: number, compareFn?: (a: T, b: T) => number) { super(); this.array = new Array(length); - this._initSize = length; - this._compareFn = compareFn; + this._initSize$ = length; + this._compareFn$ = compareFn; } /** @@ -132,7 +132,7 @@ export class CachedArray extends ScalableContainer { */ public tryShrink (): void { if (this.array.length >> 2 > this.length) { - this.array.length = Math.max(this._initSize, this.array.length >> 1); + this.array.length = Math.max(this._initSize$, this.array.length >> 1); } } @@ -145,7 +145,7 @@ export class CachedArray extends ScalableContainer { */ public sort (): void { this.array.length = this.length; - this.array.sort(this._compareFn); + this.array.sort(this._compareFn$); } /** diff --git a/cocos/core/memop/pool.ts b/cocos/core/memop/pool.ts index ee9c538e908..eb29e7ae410 100644 --- a/cocos/core/memop/pool.ts +++ b/cocos/core/memop/pool.ts @@ -33,12 +33,12 @@ import { ScalableContainer } from './scalable-container'; * @see [[RecyclePool]] */ export class Pool extends ScalableContainer { - private declare _ctor: () => T; - private declare _elementsPerBatch: number; - private declare _shrinkThreshold: number; - private declare _nextAvail: number; - private _freePool: T[] = []; - private declare _dtor: ((obj: T) => void) | null; + private declare _ctor$: () => T; + private declare _elementsPerBatch$: number; + private declare _shrinkThreshold$: number; + private declare _nextAvail$: number; + private _freePool$: T[] = []; + private declare _dtor$: ((obj: T) => void) | null; /** * @en Constructor with the allocator of elements and initial pool size. @@ -58,14 +58,14 @@ export class Pool extends ScalableContainer { */ constructor (ctor: () => T, elementsPerBatch: number, dtor?: (obj: T) => void, shrinkThreshold?: number) { super(); - this._ctor = ctor; - this._dtor = dtor || null; - this._elementsPerBatch = Math.max(elementsPerBatch, 1); - this._shrinkThreshold = shrinkThreshold ? max(shrinkThreshold, 1) : this._elementsPerBatch; - this._nextAvail = this._elementsPerBatch - 1; - - for (let i = 0; i < this._elementsPerBatch; ++i) { - this._freePool.push(ctor()); + this._ctor$ = ctor; + this._dtor$ = dtor || null; + this._elementsPerBatch$ = Math.max(elementsPerBatch, 1); + this._shrinkThreshold$ = shrinkThreshold ? max(shrinkThreshold, 1) : this._elementsPerBatch$; + this._nextAvail$ = this._elementsPerBatch$ - 1; + + for (let i = 0; i < this._elementsPerBatch$; ++i) { + this._freePool$.push(ctor()); } } @@ -76,15 +76,15 @@ export class Pool extends ScalableContainer { * @zh 该函数总是返回一个可用的对象。 */ public alloc (): T { - if (this._nextAvail < 0) { - this._freePool.length = this._elementsPerBatch; - for (let i = 0; i < this._elementsPerBatch; i++) { - this._freePool[i] = this._ctor(); + if (this._nextAvail$ < 0) { + this._freePool$.length = this._elementsPerBatch$; + for (let i = 0; i < this._elementsPerBatch$; i++) { + this._freePool$[i] = this._ctor$(); } - this._nextAvail = this._elementsPerBatch - 1; + this._nextAvail$ = this._elementsPerBatch$ - 1; } - return this._freePool[this._nextAvail--]; + return this._freePool$[this._nextAvail$--]; } /** @@ -94,7 +94,7 @@ export class Pool extends ScalableContainer { * @zh 放回对象池中的对象。 */ public free (obj: T): void { - this._freePool[++this._nextAvail] = obj; + this._freePool$[++this._nextAvail$] = obj; } /** @@ -104,9 +104,9 @@ export class Pool extends ScalableContainer { * @zh 放回对象池中的一组对象。 */ public freeArray (objs: T[]): void { - this._freePool.length = this._nextAvail + 1; - Array.prototype.push.apply(this._freePool, objs); - this._nextAvail += objs.length; + this._freePool$.length = this._nextAvail$ + 1; + Array.prototype.push.apply(this._freePool$, objs); + this._nextAvail$ += objs.length; } /** @@ -114,25 +114,25 @@ export class Pool extends ScalableContainer { * @zh 尝试缩容对象池,以释放内存。 */ public tryShrink (): void { - const freeObjectNumber = this._nextAvail + 1; - if (freeObjectNumber <= this._shrinkThreshold) { + const freeObjectNumber = this._nextAvail$ + 1; + if (freeObjectNumber <= this._shrinkThreshold$) { return; } let objectNumberToShrink = 0; - if (freeObjectNumber >> 1 >= this._shrinkThreshold) { + if (freeObjectNumber >> 1 >= this._shrinkThreshold$) { objectNumberToShrink = freeObjectNumber >> 1; } else { - objectNumberToShrink = Math.floor((freeObjectNumber - this._shrinkThreshold + 1) / 2); + objectNumberToShrink = Math.floor((freeObjectNumber - this._shrinkThreshold$ + 1) / 2); } - if (this._dtor) { - for (let i = this._nextAvail - objectNumberToShrink + 1; i <= this._nextAvail; ++i) { - this._dtor(this._freePool[i]); + if (this._dtor$) { + for (let i = this._nextAvail$ - objectNumberToShrink + 1; i <= this._nextAvail$; ++i) { + this._dtor$(this._freePool$[i]); } } - this._nextAvail -= objectNumberToShrink; - this._freePool.length = this._nextAvail + 1; + this._nextAvail$ -= objectNumberToShrink; + this._freePool$.length = this._nextAvail$ + 1; } /** @@ -142,14 +142,14 @@ export class Pool extends ScalableContainer { public destroy (): void { const dtor = arguments.length > 0 ? arguments[0] : null; if (dtor) { warnID(14100); } - const readDtor = dtor || this._dtor; + const readDtor = dtor || this._dtor$; if (readDtor) { - for (let i = 0; i <= this._nextAvail; i++) { - readDtor(this._freePool[i]); + for (let i = 0; i <= this._nextAvail$; i++) { + readDtor(this._freePool$[i]); } } - this._freePool.length = 0; - this._nextAvail = -1; + this._freePool$.length = 0; + this._nextAvail$ = -1; super.destroy(); } } diff --git a/cocos/core/memop/recycle-pool.ts b/cocos/core/memop/recycle-pool.ts index ac1fc144c3a..1b15e284fa6 100644 --- a/cocos/core/memop/recycle-pool.ts +++ b/cocos/core/memop/recycle-pool.ts @@ -38,9 +38,9 @@ import { ScalableContainer } from './scalable-container'; export class RecyclePool extends ScalableContainer { private declare _fn: () => T; private declare _dtor: ((obj: T) => void) | null; - private _count = 0; - private declare _data: T[]; - private declare _initSize: number; + private _count$ = 0; + private declare _data$: T[]; + private declare _initSize$: number; /** * @en Constructor with the allocator of elements and initial pool size, all elements will be pre-allocated. @@ -53,11 +53,11 @@ export class RecyclePool extends ScalableContainer { super(); this._fn = fn; this._dtor = dtor || null; - this._data = new Array(size); - this._initSize = size; + this._data$ = new Array(size); + this._initSize$ = size; for (let i = 0; i < size; ++i) { - this._data[i] = fn(); + this._data$[i] = fn(); } } @@ -66,7 +66,7 @@ export class RecyclePool extends ScalableContainer { * @zh 对象池大小。 */ get length (): number { - return this._count; + return this._count$; } /** @@ -74,7 +74,7 @@ export class RecyclePool extends ScalableContainer { * @zh 实际对象池数组。 */ get data (): T[] { - return this._data; + return this._data$; } /** @@ -82,7 +82,7 @@ export class RecyclePool extends ScalableContainer { * @zh 清空对象池。目前仅仅会设置尺寸为 0。 */ public reset (): void { - this._count = 0; + this._count$ = 0; } /** @@ -91,9 +91,9 @@ export class RecyclePool extends ScalableContainer { * @param size @en The new size of the pool. @zh 新的对象池大小。 */ public resize (size: number): void { - if (size > this._data.length) { - for (let i = this._data.length; i < size; ++i) { - this._data[i] = this._fn(); + if (size > this._data$.length) { + for (let i = this._data$.length; i < size; ++i) { + this._data$[i] = this._fn(); } } } @@ -103,11 +103,11 @@ export class RecyclePool extends ScalableContainer { * @zh 扩充对象池容量,会自动扩充尺寸到原来的 2 倍,并填充新的元素。 */ public add (): T { - if (this._count >= this._data.length) { - this.resize(this._data.length << 1); + if (this._count$ >= this._data$.length) { + this.resize(this._data$.length << 1); } - return this._data[this._count++]; + return this._data$[this._count$++]; } /** @@ -116,12 +116,12 @@ export class RecyclePool extends ScalableContainer { */ public destroy (): void { if (this._dtor) { - for (let i = 0; i < this._data.length; i++) { - this._dtor(this._data[i]); + for (let i = 0; i < this._data$.length; i++) { + this._dtor(this._data$[i]); } } - this._data.length = 0; - this._count = 0; + this._data$.length = 0; + this._count$ = 0; super.destroy(); } @@ -130,14 +130,14 @@ export class RecyclePool extends ScalableContainer { * @zh 尝试回收没用的对象,释放内存。 */ public tryShrink (): void { - if (this._data.length >> 2 > this._count) { - const length = Math.max(this._initSize, this._data.length >> 1); + if (this._data$.length >> 2 > this._count$) { + const length = Math.max(this._initSize$, this._data$.length >> 1); if (this._dtor) { - for (let i = length; i < this._data.length; i++) { - this._dtor(this._data[i]); + for (let i = length; i < this._data$.length; i++) { + this._dtor(this._data$[i]); } } - this._data.length = length; + this._data$.length = length; } } @@ -147,14 +147,14 @@ export class RecyclePool extends ScalableContainer { * @param idx @en The index of the element to remove. @zh 被移除的元素的索引。 */ public removeAt (idx: number): void { - if (idx >= this._count) { + if (idx >= this._count$) { return; } - const last = this._count - 1; - const tmp = this._data[idx]; - this._data[idx] = this._data[last]; - this._data[last] = tmp; - this._count -= 1; + const last = this._count$ - 1; + const tmp = this._data$[idx]; + this._data$[idx] = this._data$[last]; + this._data$[last] = tmp; + this._count$ -= 1; } } diff --git a/cocos/core/memop/scalable-container.ts b/cocos/core/memop/scalable-container.ts index 63a8ef89055..52be6d1d3ee 100644 --- a/cocos/core/memop/scalable-container.ts +++ b/cocos/core/memop/scalable-container.ts @@ -44,8 +44,8 @@ export abstract class ScalableContainer { * It will shrink all managed ScalableContainer in a fixed interval. */ class ScalableContainerManager { - private _pools: ScalableContainer[] = []; - private _lastShrinkPassed = 0; + private _pools$: ScalableContainer[] = []; + private _lastShrinkPassed$ = 0; /** * @en Shrink interval in seconds. */ @@ -57,8 +57,8 @@ class ScalableContainerManager { */ addContainer (pool: ScalableContainer): void { if (pool._poolHandle !== -1) return; - pool._poolHandle = this._pools.length; - this._pools.push(pool); + pool._poolHandle = this._pools$.length; + this._pools$.push(pool); } /** @@ -67,8 +67,8 @@ class ScalableContainerManager { */ removeContainer (pool: ScalableContainer): void { if (pool._poolHandle === -1) return; - this._pools[this._pools.length - 1]._poolHandle = pool._poolHandle; - fastRemoveAt(this._pools, pool._poolHandle); + this._pools$[this._pools$.length - 1]._poolHandle = pool._poolHandle; + fastRemoveAt(this._pools$, pool._poolHandle); pool._poolHandle = -1; } @@ -76,8 +76,8 @@ class ScalableContainerManager { * @en Try to shrink all managed ScalableContainers. */ tryShrink (): void { - for (let i = 0; i < this._pools.length; i++) { - this._pools[i].tryShrink(); + for (let i = 0; i < this._pools$.length; i++) { + this._pools$[i].tryShrink(); } } @@ -86,10 +86,10 @@ class ScalableContainerManager { * @param dt @en Delta time of frame interval in secondes. */ update (dt: number): void { - this._lastShrinkPassed += dt; - if (this._lastShrinkPassed > this.shrinkTimeSpan) { + this._lastShrinkPassed$ += dt; + if (this._lastShrinkPassed$ > this.shrinkTimeSpan) { this.tryShrink(); - this._lastShrinkPassed -= this.shrinkTimeSpan; + this._lastShrinkPassed$ -= this.shrinkTimeSpan; } } } diff --git a/cocos/core/platform/macro.ts b/cocos/core/platform/macro.ts index deeef737523..9d91165fc90 100644 --- a/cocos/core/platform/macro.ts +++ b/cocos/core/platform/macro.ts @@ -27,7 +27,7 @@ import { EDITOR, MINIGAME, NATIVE, PREVIEW, RUNTIME_BASED } from 'internal:constants'; import { legacyCC } from '../global-exports'; -import { Settings, settings } from '../settings'; +import { settings, SettingsCategory } from '../settings'; import { Orientation } from '../../../pal/screen-adapter/enum-type'; const SUPPORT_TEXTURE_FORMATS = ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png']; @@ -1131,7 +1131,7 @@ const macro: Macro = { if (NATIVE || MINIGAME || RUNTIME_BASED) { this.CLEANUP_IMAGE_CACHE = true; } - const defaultValues = settings.querySettings(Settings.Category.ENGINE, 'macros'); + const defaultValues = settings.querySettings(SettingsCategory.ENGINE, 'macros'); if (defaultValues) { for (const key in defaultValues) { macro[key] = defaultValues[key]; diff --git a/cocos/core/platform/screen.ts b/cocos/core/platform/screen.ts index 97cffce324a..b5a4d0606a3 100644 --- a/cocos/core/platform/screen.ts +++ b/cocos/core/platform/screen.ts @@ -25,10 +25,10 @@ THE SOFTWARE. */ -import { IScreenOptions, screenAdapter } from 'pal/screen-adapter'; +import { screenAdapter } from 'pal/screen-adapter'; import { legacyCC } from '../global-exports'; import { Size } from '../math'; -import { Settings, settings } from '../settings'; +import { settings, SettingsCategory } from '../settings'; import { error, warn, warnID } from './debug'; import { PalScreenEvent } from '../../../pal/screen-adapter/enum-type'; /** @@ -40,9 +40,9 @@ export class Screen { * @internal */ public init (): void { - const exactFitScreen = settings.querySettings(Settings.Category.SCREEN, 'exactFitScreen') ?? true; - const orientation = settings.querySettings(Settings.Category.SCREEN, 'orientation') ?? 'auto'; - const isHeadlessMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode') === 3; + 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 director = legacyCC.director; if (!director.root?.pipeline) { diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index 924be4eb13a..100708198d8 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -47,12 +47,12 @@ export interface ISchedulable { */ class ListEntry { public static get (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean): ListEntry { - let result = ListEntry._listEntries.pop(); + let result = ListEntry._listEntries$.pop(); if (result) { - result.target = target; - result.priority = priority; - result.paused = paused; - result.markedForDeletion = markedForDeletion; + result.target$ = target; + result.priority$ = priority; + result.paused$ = paused; + result.markedForDeletion$ = markedForDeletion; } else { result = new ListEntry(target, priority, paused, markedForDeletion); } @@ -60,18 +60,18 @@ class ListEntry { } public static put (entry: ListEntry): void { - if (ListEntry._listEntries.length < MAX_POOL_SIZE) { - entry.target = null; - ListEntry._listEntries.push(entry); + if (ListEntry._listEntries$.length < MAX_POOL_SIZE) { + entry.target$ = null; + ListEntry._listEntries$.push(entry); } } - private static _listEntries: ListEntry[] = []; + private static _listEntries$: ListEntry[] = []; - public target: ISchedulable | null; - public priority: number; - public paused: boolean; - public markedForDeletion: boolean; + public target$: ISchedulable | null; + public priority$: number; + public paused$: boolean; + public markedForDeletion$: boolean; /** * @en The constructor of ListEntry. @@ -90,10 +90,10 @@ class ListEntry { * @zh 删除标记, 当为true时, selector 将不再被调用,并且entry将在下一个tick结束时被删除。 */ constructor (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean) { - this.target = target; - this.priority = priority; - this.paused = paused; - this.markedForDeletion = markedForDeletion; + this.target$ = target; + this.priority$ = priority; + this.paused$ = paused; + this.markedForDeletion$ = markedForDeletion; } } @@ -110,10 +110,10 @@ class HashUpdateEntry { public static get (list: ListEntry[], entry: ListEntry, target: ISchedulable, callback: AnyFunction | null): HashUpdateEntry { let result = HashUpdateEntry._hashUpdateEntries.pop(); if (result) { - result.list = list; - result.entry = entry; - result.target = target; - result.callback = callback; + result.list$ = list; + result.entry$ = entry; + result.target$ = target; + result.callback$ = callback; } else { result = new HashUpdateEntry(list, entry, target, callback); } @@ -122,23 +122,23 @@ class HashUpdateEntry { public static put (entry: HashUpdateEntry): void { if (HashUpdateEntry._hashUpdateEntries.length < MAX_POOL_SIZE) { - entry.list = entry.entry = entry.target = entry.callback = null; + entry.list$ = entry.entry$ = entry.target$ = entry.callback$ = null; HashUpdateEntry._hashUpdateEntries.push(entry); } } private static _hashUpdateEntries: HashUpdateEntry[] = []; - public list: ListEntry[] | null; - public entry: ListEntry | null; - public target: ISchedulable | null; - public callback: AnyFunction | null; + public list$: ListEntry[] | null; + public entry$: ListEntry | null; + public target$: ISchedulable | null; + public callback$: AnyFunction | null; constructor (list: ListEntry[], entry: ListEntry, target: ISchedulable, callback: AnyFunction | null) { - this.list = list; - this.entry = entry; - this.target = target; - this.callback = callback; + this.list$ = list; + this.entry$ = entry; + this.target$ = target; + this.callback$ = callback; } } @@ -154,14 +154,14 @@ class HashUpdateEntry { */ class HashTimerEntry { public static get (timers: CallbackTimer[] | null, target: ISchedulable, timerIndex: number, currentTimer: CallbackTimer | null, currentTimerSalvaged: boolean, paused: boolean): HashTimerEntry { - let result = HashTimerEntry._hashTimerEntries.pop(); + let result = HashTimerEntry._hashTimerEntries$.pop(); if (result) { - result.timers = timers; - result.target = target; - result.timerIndex = timerIndex; - result.currentTimer = currentTimer; - result.currentTimerSalvaged = currentTimerSalvaged; - result.paused = paused; + result.timers$ = timers; + result.target$ = target; + result.timerIndex$ = timerIndex; + result.currentTimer$ = currentTimer; + result.currentTimerSalvaged$ = currentTimerSalvaged; + result.paused$ = paused; } else { result = new HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused); } @@ -169,28 +169,28 @@ class HashTimerEntry { } public static put (entry: HashTimerEntry): void { - if (HashTimerEntry._hashTimerEntries.length < MAX_POOL_SIZE) { - entry.timers = entry.target = entry.currentTimer = null; - HashTimerEntry._hashTimerEntries.push(entry); + if (HashTimerEntry._hashTimerEntries$.length < MAX_POOL_SIZE) { + entry.timers$ = entry.target$ = entry.currentTimer$ = null; + HashTimerEntry._hashTimerEntries$.push(entry); } } - private static _hashTimerEntries: HashTimerEntry[] = []; + private static _hashTimerEntries$: HashTimerEntry[] = []; - public timers: CallbackTimer[] | null; - public target: ISchedulable | null; - public timerIndex: number; - public currentTimer: CallbackTimer | null; - public currentTimerSalvaged: boolean; - public paused: boolean; + public timers$: CallbackTimer[] | null; + public target$: ISchedulable | null; + public timerIndex$: number; + public currentTimer$: CallbackTimer | null; + public currentTimerSalvaged$: boolean; + public paused$: boolean; constructor (timers: CallbackTimer[] | null, target: ISchedulable, timerIndex: number, currentTimer: CallbackTimer | null, currentTimerSalvaged: boolean, paused: boolean) { - this.timers = timers; - this.target = target; - this.timerIndex = timerIndex; - this.currentTimer = currentTimer; - this.currentTimerSalvaged = currentTimerSalvaged; - this.paused = paused; + this.timers$ = timers; + this.target$ = target; + this.timerIndex$ = timerIndex; + this.currentTimer$ = currentTimer; + this.currentTimerSalvaged$ = currentTimerSalvaged; + this.paused$ = paused; } } @@ -200,54 +200,54 @@ type CallbackType = (dt?: number) => void; * Light weight timer */ class CallbackTimer { - public static _timers: CallbackTimer[] = []; - public static get (): CallbackTimer { return CallbackTimer._timers.pop() || new CallbackTimer(); } + public static _timers$: CallbackTimer[] = []; + public static get (): CallbackTimer { return CallbackTimer._timers$.pop() || new CallbackTimer(); } public static put (timer: CallbackTimer): void { - if (CallbackTimer._timers.length < MAX_POOL_SIZE && !timer._lock) { - timer._scheduler = timer._target = timer._callback = null; - CallbackTimer._timers.push(timer); + if (CallbackTimer._timers$.length < MAX_POOL_SIZE && !timer._lock$) { + timer._scheduler$ = timer._target$ = timer._callback$ = null; + CallbackTimer._timers$.push(timer); } } - private _lock: boolean; - private _scheduler: Scheduler | null; - private _elapsed: number; - private _runForever: boolean; - private _useDelay: boolean; - private _timesExecuted: number; - private _repeat: number; - private _delay: number; - private _interval: number; - private _target: ISchedulable | null; - private _callback?: CallbackType | null; + private _lock$: boolean; + private _scheduler$: Scheduler | null; + private _elapsed$: number; + private _runForever$: boolean; + private _useDelay$: boolean; + private _timesExecuted$: number; + private _repeat$: number; + private _delay$: number; + private _interval$: number; + private _target$: ISchedulable | null; + private _callback$?: CallbackType | null; constructor () { - this._lock = false; - this._scheduler = null; - this._elapsed = -1; - this._runForever = false; - this._useDelay = false; - this._timesExecuted = 0; - this._repeat = 0; - this._delay = 0; - this._interval = 0; - - this._target = null; + this._lock$ = false; + this._scheduler$ = null; + this._elapsed$ = -1; + this._runForever$ = false; + this._useDelay$ = false; + this._timesExecuted$ = 0; + this._repeat$ = 0; + this._delay$ = 0; + this._interval$ = 0; + + this._target$ = null; } public initWithCallback (scheduler: Scheduler, callback: CallbackType, target: ISchedulable, seconds: number, repeat: number, delay: number): boolean { - this._lock = false; - this._scheduler = scheduler; - this._target = target; - this._callback = callback; - this._timesExecuted = 0; - - this._elapsed = -1; - this._interval = seconds; - this._delay = delay; - this._useDelay = (this._delay > 0); - this._repeat = repeat; - this._runForever = (this._repeat === legacyCC.macro.REPEAT_FOREVER); + this._lock$ = false; + this._scheduler$ = scheduler; + this._target$ = target; + this._callback$ = callback; + this._timesExecuted$ = 0; + + this._elapsed$ = -1; + this._interval$ = seconds; + this._delay$ = delay; + this._useDelay$ = (this._delay$ > 0); + this._repeat$ = repeat; + this._runForever$ = (this._repeat$ === legacyCC.macro.REPEAT_FOREVER); return true; } /** @@ -258,14 +258,14 @@ class CallbackTimer { * @zh 返回计时器的时间间隔, 以秒为单位。 */ public getInterval (): number { - return this._interval; + return this._interval$; } /** * @en Set interval in seconds. * @zh 以秒为单位设置时间间隔。 */ public setInterval (interval: number): void { - this._interval = interval; + this._interval$ = interval; } /** @@ -276,33 +276,33 @@ class CallbackTimer { * @zh 更新间隔时间, 单位是秒。 */ public update (dt: number): void { - if (this._elapsed === -1) { - this._elapsed = 0; - this._timesExecuted = 0; + if (this._elapsed$ === -1) { + this._elapsed$ = 0; + this._timesExecuted$ = 0; } else { - this._elapsed += dt; - if (this._runForever && !this._useDelay) { // standard timer usage - if (this._elapsed >= this._interval) { + this._elapsed$ += dt; + if (this._runForever$ && !this._useDelay$) { // standard timer usage + if (this._elapsed$ >= this._interval$) { this.trigger(); - this._elapsed = 0; + this._elapsed$ = 0; } } else { // advanced usage - if (this._useDelay) { - if (this._elapsed >= this._delay) { + if (this._useDelay$) { + if (this._elapsed$ >= this._delay$) { this.trigger(); - this._elapsed -= this._delay; - this._timesExecuted += 1; - this._useDelay = false; + this._elapsed$ -= this._delay$; + this._timesExecuted$ += 1; + this._useDelay$ = false; } - } else if (this._elapsed >= this._interval) { + } else if (this._elapsed$ >= this._interval$) { this.trigger(); - this._elapsed = 0; - this._timesExecuted += 1; + this._elapsed$ = 0; + this._timesExecuted$ += 1; } - if (this._callback && !this._runForever && this._timesExecuted > this._repeat) { + if (this._callback$ && !this._runForever$ && this._timesExecuted$ > this._repeat$) { this.cancel(); } } @@ -310,20 +310,20 @@ class CallbackTimer { } public getCallback (): CallbackType | null | undefined { - return this._callback; + return this._callback$; } public trigger (): void { - if (this._target && this._callback) { - this._lock = true; - this._callback.call(this._target, this._elapsed); - this._lock = false; + if (this._target$ && this._callback$) { + this._lock$ = true; + this._callback$.call(this._target$, this._elapsed$); + this._lock$ = false; } } public cancel (): void { - if (this._scheduler && this._callback && this._target) { - this._scheduler.unscheduleForTimer(this, this._target); + if (this._scheduler$ && this._callback$ && this._target$) { + this._scheduler$.unscheduleForTimer(this, this._target$); } } } @@ -350,16 +350,16 @@ class CallbackTimer { export class Scheduler extends System { public static ID = 'scheduler'; - private _timeScale: number; - private _updatesNegList: ListEntry[]; - private _updates0List: ListEntry[]; - private _updatesPosList: ListEntry[]; - private _hashForUpdates: Record; - private _hashForTimers: Record; - private _currentTarget: HashTimerEntry | null; - private _currentTargetSalvaged: boolean; - private _updateHashLocked: boolean; - private _arrayForTimers: HashTimerEntry[]; + private _timeScale$: number; + private _updatesNegList$: ListEntry[]; + private _updates0List$: ListEntry[]; + private _updatesPosList$: ListEntry[]; + private _hashForUpdates$: Record; + private _hashForTimers$: Record; + private _currentTarget$: HashTimerEntry | null; + private _currentTargetSalvaged$: boolean; + private _updateHashLocked$: boolean; + private _arrayForTimers$: HashTimerEntry[]; /** * @en This method should be called for any target which needs to schedule tasks, and this method should be called before any scheduler API usage. @@ -384,17 +384,17 @@ export class Scheduler extends System { constructor () { super(); - this._timeScale = 1.0; - this._updatesNegList = []; // list of priority < 0 - this._updates0List = []; // list of priority == 0 - this._updatesPosList = []; // list of priority > 0 - this._hashForUpdates = createMap(true) as Record; // hash used to fetch quickly the list entries for pause, delete, etc - this._hashForTimers = createMap(true) as Record; // Used for "selectors with interval" - this._currentTarget = null; - this._currentTargetSalvaged = false; - this._updateHashLocked = false; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. - - this._arrayForTimers = []; // Speed up indexing + this._timeScale$ = 1.0; + this._updatesNegList$ = []; // list of priority < 0 + this._updates0List$ = []; // list of priority == 0 + this._updatesPosList$ = []; // list of priority > 0 + this._hashForUpdates$ = createMap(true) as Record; // hash used to fetch quickly the list entries for pause, delete, etc + this._hashForTimers$ = createMap(true) as Record; // Used for "selectors with interval" + this._currentTarget$ = null; + this._currentTargetSalvaged$ = false; + this._updateHashLocked$ = false; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. + + this._arrayForTimers$ = []; // Speed up indexing // this._arrayForUpdates = []; // Speed up indexing } @@ -416,7 +416,7 @@ export class Scheduler extends System { * @param timeScale */ public setTimeScale (timeScale: number): void { - this._timeScale = timeScale; + this._timeScale$ = timeScale; } /** @@ -424,7 +424,7 @@ export class Scheduler extends System { * @zh 获取时间间隔的缩放比例。 */ public getTimeScale (): number { - return this._timeScale; + return this._timeScale$; } /** @@ -435,9 +435,9 @@ export class Scheduler extends System { * @zh 更新间隔时间, 单位是秒。 */ public update (dt: number): void { - this._updateHashLocked = true; - if (this._timeScale !== 1) { - dt *= this._timeScale; + this._updateHashLocked$ = true; + if (this._timeScale$ !== 1) { + dt *= this._timeScale$; } let i: number; @@ -445,84 +445,84 @@ export class Scheduler extends System { let len: number; let entry: ListEntry; - for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) { + for (i = 0, list = this._updatesNegList$, len = list.length; i < len; i++) { entry = list[i]; - if (!entry.paused && !entry.markedForDeletion && entry.target) { - entry.target.update?.(dt); + if (!entry.paused$ && !entry.markedForDeletion$ && entry.target$) { + entry.target$.update?.(dt); } } - for (i = 0, list = this._updates0List, len = list.length; i < len; i++) { + for (i = 0, list = this._updates0List$, len = list.length; i < len; i++) { entry = list[i]; - if (!entry.paused && !entry.markedForDeletion && entry.target) { - entry.target.update?.(dt); + if (!entry.paused$ && !entry.markedForDeletion$ && entry.target$) { + entry.target$.update?.(dt); } } - for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) { + for (i = 0, list = this._updatesPosList$, len = list.length; i < len; i++) { entry = list[i]; - if (!entry.paused && !entry.markedForDeletion && entry.target) { - entry.target.update?.(dt); + if (!entry.paused$ && !entry.markedForDeletion$ && entry.target$) { + entry.target$.update?.(dt); } } // Iterate over all the custom selectors let elt: HashTimerEntry; - const arr = this._arrayForTimers; + const arr = this._arrayForTimers$; for (i = 0; i < arr.length; i++) { elt = arr[i]; - this._currentTarget = elt; - this._currentTargetSalvaged = false; + this._currentTarget$ = elt; + this._currentTargetSalvaged$ = false; - if (!elt.paused && elt.timers) { + if (!elt.paused$ && elt.timers$) { // The 'timers' array may change while inside this loop - for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++(elt.timerIndex)) { - elt.currentTimer = elt.timers[elt.timerIndex]; - elt.currentTimerSalvaged = false; + for (elt.timerIndex$ = 0; elt.timerIndex$ < elt.timers$.length; ++(elt.timerIndex$)) { + elt.currentTimer$ = elt.timers$[elt.timerIndex$]; + elt.currentTimerSalvaged$ = false; - elt.currentTimer.update(dt); - elt.currentTimer = null; + elt.currentTimer$.update(dt); + elt.currentTimer$ = null; } } // only delete currentTarget if no actions were scheduled during the cycle (issue #481) - if (this._currentTargetSalvaged && this._currentTarget.timers?.length === 0) { - this._removeHashElement(this._currentTarget); + if (this._currentTargetSalvaged$ && this._currentTarget$.timers$?.length === 0) { + this._removeHashElement$(this._currentTarget$); --i; } } // delete all updates that are marked for deletion // updates with priority < 0 - for (i = 0, list = this._updatesNegList; i < list.length;) { + for (i = 0, list = this._updatesNegList$; i < list.length;) { entry = list[i]; - if (entry.markedForDeletion) { - this._removeUpdateFromHash(entry); + if (entry.markedForDeletion$) { + this._removeUpdateFromHash$(entry); } else { i++; } } - for (i = 0, list = this._updates0List; i < list.length;) { + for (i = 0, list = this._updates0List$; i < list.length;) { entry = list[i]; - if (entry.markedForDeletion) { - this._removeUpdateFromHash(entry); + if (entry.markedForDeletion$) { + this._removeUpdateFromHash$(entry); } else { i++; } } - for (i = 0, list = this._updatesPosList; i < list.length;) { + for (i = 0, list = this._updatesPosList$; i < list.length;) { entry = list[i]; - if (entry.markedForDeletion) { - this._removeUpdateFromHash(entry); + if (entry.markedForDeletion$) { + this._removeUpdateFromHash$(entry); } else { i++; } } - this._updateHashLocked = false; - this._currentTarget = null; + this._updateHashLocked$ = false; + this._currentTarget$ = null; } /** @@ -603,23 +603,23 @@ export class Scheduler extends System { errorID(1510); return; } - let element = this._hashForTimers[targetId]; + let element = this._hashForTimers$[targetId]; if (!element) { // Is this the 1st element ? Then set the pause level to all the callback_fns of this target element = HashTimerEntry.get(null, target, 0, null, false, Boolean(paused)); - this._arrayForTimers.push(element); - this._hashForTimers[targetId] = element; - } else if (element.paused !== paused) { + this._arrayForTimers$.push(element); + this._hashForTimers$[targetId] = element; + } else if (element.paused$ !== paused) { warnID(1511); } let timer: CallbackTimer; let i; - if (element.timers == null) { - element.timers = []; + if (element.timers$ == null) { + element.timers$ = []; } else { - for (i = 0; i < element.timers.length; ++i) { - timer = element.timers[i]; + for (i = 0; i < element.timers$.length; ++i) { + timer = element.timers$[i]; if (timer && callback === timer.getCallback()) { logID(1507, timer.getInterval(), interval); timer.setInterval(interval); @@ -630,10 +630,10 @@ export class Scheduler extends System { timer = CallbackTimer.get(); timer.initWithCallback(this, callback, target, interval, repeat ?? 0, delay ?? 0); - element.timers.push(timer); + element.timers$.push(timer); - if (this._currentTarget === element && this._currentTargetSalvaged) { - this._currentTargetSalvaged = false; + if (this._currentTarget$ === element && this._currentTargetSalvaged$) { + this._currentTargetSalvaged$ = false; } } @@ -658,22 +658,22 @@ export class Scheduler extends System { errorID(1510); return; } - const hashElement = this._hashForUpdates[targetId]; - if (hashElement && hashElement.entry) { + const hashElement = this._hashForUpdates$[targetId]; + if (hashElement && hashElement.entry$) { // check if priority has changed - if (hashElement.entry.priority !== priority) { - if (this._updateHashLocked) { + if (hashElement.entry$.priority$ !== priority) { + if (this._updateHashLocked$) { logID(1506); - hashElement.entry.markedForDeletion = false; - hashElement.entry.paused = paused; + hashElement.entry$.markedForDeletion$ = false; + hashElement.entry$.paused$ = paused; return; } else { // will be added again outside if (hashElement). this.unscheduleUpdate(target); } } else { - hashElement.entry.markedForDeletion = false; - hashElement.entry.paused = paused; + hashElement.entry$.markedForDeletion$ = false; + hashElement.entry$.paused$ = paused; return; } } @@ -684,15 +684,15 @@ export class Scheduler extends System { // most of the updates are going to be 0, that's way there // is an special list for updates with priority 0 if (priority === 0) { - ppList = this._updates0List; - this._appendIn(ppList, listElement); + ppList = this._updates0List$; + this._appendIn$(ppList, listElement); } else { - ppList = priority < 0 ? this._updatesNegList : this._updatesPosList; - this._priorityIn(ppList, listElement, priority); + ppList = priority < 0 ? this._updatesNegList$ : this._updatesPosList$; + this._priorityIn$(ppList, listElement, priority); } // update hash entry for quick access - this._hashForUpdates[targetId] = HashUpdateEntry.get(ppList, listElement, target, null); + this._hashForUpdates$[targetId] = HashUpdateEntry.get(ppList, listElement, target, null); } /** @@ -718,30 +718,30 @@ export class Scheduler extends System { return; } - const element = this._hashForTimers[targetId]; + const element = this._hashForTimers$[targetId]; if (element) { - const timers = element.timers; + const timers = element.timers$; if (!timers) { return; } for (let i = 0, li = timers.length; i < li; i++) { const timer = timers[i]; if (callback === timer.getCallback()) { - if ((timer === element.currentTimer) && (!element.currentTimerSalvaged)) { - element.currentTimerSalvaged = true; + if ((timer === element.currentTimer$) && (!element.currentTimerSalvaged$)) { + element.currentTimerSalvaged$ = true; } timers.splice(i, 1); CallbackTimer.put(timer); // update timerIndex in case we are in tick;, looping over the actions - if (element.timerIndex >= i) { - element.timerIndex--; + if (element.timerIndex$ >= i) { + element.timerIndex$--; } if (timers.length === 0) { - if (this._currentTarget === element) { - this._currentTargetSalvaged = true; + if (this._currentTarget$ === element) { + this._currentTargetSalvaged$ = true; } else { - this._removeHashElement(element); + this._removeHashElement$(element); } } return; @@ -758,8 +758,8 @@ export class Scheduler extends System { */ public unscheduleForTimer (timerToUnschedule: CallbackTimer, target: ISchedulable): void { const targetId = (target.uuid || target.id) as string; - const element = this._hashForTimers[targetId]; - const timers = element.timers; + const element = this._hashForTimers$[targetId]; + const timers = element.timers$; if (!timers || timers.length === 0) { return; } @@ -771,12 +771,12 @@ export class Scheduler extends System { CallbackTimer.put(timer); // update timerIndex in case we are in tick;, looping over the actions - if (element.timerIndex >= i) { - element.timerIndex--; + if (element.timerIndex$ >= i) { + element.timerIndex$--; } if (timers.length === 0) { - this._currentTargetSalvaged = true; + this._currentTargetSalvaged$ = true; } return; } @@ -798,12 +798,12 @@ export class Scheduler extends System { return; } - const element = this._hashForUpdates[targetId]; - if (element?.entry) { - if (this._updateHashLocked) { - element.entry.markedForDeletion = true; + const element = this._hashForUpdates$[targetId]; + if (element?.entry$) { + if (this._updateHashLocked$) { + element.entry$.markedForDeletion$ = true; } else { - this._removeUpdateFromHash(element.entry); + this._removeUpdateFromHash$(element.entry$); } } } @@ -827,22 +827,22 @@ export class Scheduler extends System { } // Custom Selectors - const element = this._hashForTimers[targetId]; - if (element?.timers) { - const timers = element.timers; - if (element.currentTimer && timers.indexOf(element.currentTimer) > -1 - && (!element.currentTimerSalvaged)) { - element.currentTimerSalvaged = true; + const element = this._hashForTimers$[targetId]; + if (element?.timers$) { + const timers = element.timers$; + if (element.currentTimer$ && timers.indexOf(element.currentTimer$) > -1 + && (!element.currentTimerSalvaged$)) { + element.currentTimerSalvaged$ = true; } for (let i = 0, l = timers.length; i < l; i++) { CallbackTimer.put(timers[i]); } timers.length = 0; - if (this._currentTarget === element) { - this._currentTargetSalvaged = true; + if (this._currentTarget$ === element) { + this._currentTargetSalvaged$ = true; } else { - this._removeHashElement(element); + this._removeHashElement$(element); } } @@ -879,11 +879,11 @@ export class Scheduler extends System { // Custom Selectors let i: number; let element: HashTimerEntry; - const arr = this._arrayForTimers; + const arr = this._arrayForTimers$; for (i = arr.length - 1; i >= 0; i--) { element = arr[i]; - if (element.target) { - this.unscheduleAllForTarget(element.target); + if (element.target$) { + this.unscheduleAllForTarget(element.target$); } } @@ -891,38 +891,38 @@ export class Scheduler extends System { let entry: ListEntry; let temp_length = 0; if (minPriority < 0) { - for (i = 0; i < this._updatesNegList.length;) { - temp_length = this._updatesNegList.length; - entry = this._updatesNegList[i]; - if (entry?.target && entry.priority >= minPriority) { - this.unscheduleUpdate(entry.target); + for (i = 0; i < this._updatesNegList$.length;) { + temp_length = this._updatesNegList$.length; + entry = this._updatesNegList$[i]; + if (entry?.target$ && entry.priority$ >= minPriority) { + this.unscheduleUpdate(entry.target$); } - if (temp_length === this._updatesNegList.length) { + if (temp_length === this._updatesNegList$.length) { i++; } } } if (minPriority <= 0) { - for (i = 0; i < this._updates0List.length;) { - temp_length = this._updates0List.length; - entry = this._updates0List[i]; - if (entry?.target) { - this.unscheduleUpdate(entry.target); + for (i = 0; i < this._updates0List$.length;) { + temp_length = this._updates0List$.length; + entry = this._updates0List$[i]; + if (entry?.target$) { + this.unscheduleUpdate(entry.target$); } - if (temp_length === this._updates0List.length) { + if (temp_length === this._updates0List$.length) { i++; } } } - for (i = 0; i < this._updatesPosList.length;) { - temp_length = this._updatesPosList.length; - entry = this._updatesPosList[i]; - if (entry?.target && entry.priority >= minPriority) { - this.unscheduleUpdate(entry.target); + for (i = 0; i < this._updatesPosList$.length;) { + temp_length = this._updatesPosList$.length; + entry = this._updatesPosList$[i]; + if (entry?.target$ && entry.priority$ >= minPriority) { + this.unscheduleUpdate(entry.target$); } - if (temp_length === this._updatesPosList.length) { + if (temp_length === this._updatesPosList$.length) { i++; } } @@ -946,16 +946,16 @@ export class Scheduler extends System { return false; } - const element = this._hashForTimers[targetId]; + const element = this._hashForTimers$[targetId]; if (!element) { return false; } - if (element.timers == null) { + if (element.timers$ == null) { return false; } else { - const timers = element.timers; + const timers = element.timers$; for (let i = 0; i < timers.length; ++i) { const timer = timers[i]; @@ -992,47 +992,47 @@ export class Scheduler extends System { const idsWithSelectors: ISchedulable[] = []; let element: HashTimerEntry; - const locArrayForTimers = this._arrayForTimers; + const locArrayForTimers = this._arrayForTimers$; let i; let li; // Custom Selectors for (i = 0, li = locArrayForTimers.length; i < li; i++) { element = locArrayForTimers[i]; - if (element?.target) { - element.paused = true; - idsWithSelectors.push(element.target); + if (element?.target$) { + element.paused$ = true; + idsWithSelectors.push(element.target$); } } let entry: ListEntry; if (minPriority < 0) { - for (i = 0; i < this._updatesNegList.length; i++) { - entry = this._updatesNegList[i]; - if (entry?.target) { - if (entry.priority >= minPriority) { - entry.paused = true; - idsWithSelectors.push(entry.target); + for (i = 0; i < this._updatesNegList$.length; i++) { + entry = this._updatesNegList$[i]; + if (entry?.target$) { + if (entry.priority$ >= minPriority) { + entry.paused$ = true; + idsWithSelectors.push(entry.target$); } } } } if (minPriority <= 0) { - for (i = 0; i < this._updates0List.length; i++) { - entry = this._updates0List[i]; - if (entry?.target) { - entry.paused = true; - idsWithSelectors.push(entry.target); + for (i = 0; i < this._updates0List$.length; i++) { + entry = this._updates0List$[i]; + if (entry?.target$) { + entry.paused$ = true; + idsWithSelectors.push(entry.target$); } } } - for (i = 0; i < this._updatesPosList.length; i++) { - entry = this._updatesPosList[i]; - if (entry?.target) { - if (entry.priority >= minPriority) { - entry.paused = true; - idsWithSelectors.push(entry.target); + for (i = 0; i < this._updatesPosList$.length; i++) { + entry = this._updatesPosList$[i]; + if (entry?.target$) { + if (entry.priority$ >= minPriority) { + entry.paused$ = true; + idsWithSelectors.push(entry.target$); } } } @@ -1079,15 +1079,15 @@ export class Scheduler extends System { } // customer selectors - const element = this._hashForTimers[targetId]; + const element = this._hashForTimers$[targetId]; if (element) { - element.paused = true; + element.paused$ = true; } // update callback - const elementUpdate = this._hashForUpdates[targetId]; - if (elementUpdate?.entry) { - elementUpdate.entry.paused = true; + const elementUpdate = this._hashForUpdates$[targetId]; + if (elementUpdate?.entry$) { + elementUpdate.entry$.paused$ = true; } } @@ -1111,15 +1111,15 @@ export class Scheduler extends System { } // custom selectors - const element = this._hashForTimers[targetId]; + const element = this._hashForTimers$[targetId]; if (element) { - element.paused = false; + element.paused$ = false; } // update callback - const elementUpdate = this._hashForUpdates[targetId]; - if (elementUpdate?.entry) { - elementUpdate.entry.paused = false; + const elementUpdate = this._hashForUpdates$[targetId]; + if (elementUpdate?.entry$) { + elementUpdate.entry$.paused$ = false; } } @@ -1137,28 +1137,28 @@ export class Scheduler extends System { } // Custom selectors - const element = this._hashForTimers[targetId]; + const element = this._hashForTimers$[targetId]; if (element) { - return element.paused; + return element.paused$; } - const elementUpdate = this._hashForUpdates[targetId]; - if (elementUpdate?.entry) { - return elementUpdate.entry.paused; + const elementUpdate = this._hashForUpdates$[targetId]; + if (elementUpdate?.entry$) { + return elementUpdate.entry$.paused$; } return false; } // -----------------------private method---------------------- - private _removeHashElement (element: HashTimerEntry): void { - if (!element.target) { + private _removeHashElement$ (element: HashTimerEntry): void { + if (!element.target$) { return; } - const targetId = element.target.uuid || element.target.id; + const targetId = element.target$.uuid || element.target$.id; if (typeof targetId === 'undefined') { return; } - delete this._hashForTimers[targetId]; - const arr = this._arrayForTimers; + delete this._hashForTimers$[targetId]; + const arr = this._arrayForTimers$; for (let i = 0, l = arr.length; i < l; i++) { if (arr[i] === element) { arr.splice(i, 1); @@ -1168,19 +1168,19 @@ export class Scheduler extends System { HashTimerEntry.put(element); } - private _removeUpdateFromHash (entry: ListEntry): void { - if (!entry.target) { + private _removeUpdateFromHash$ (entry: ListEntry): void { + if (!entry.target$) { return; } - const targetId = entry.target.uuid || entry.target.id; + const targetId = entry.target$.uuid || entry.target$.id; if (typeof targetId === 'undefined') { return; } - const element = this._hashForUpdates[targetId]; + const element = this._hashForUpdates$[targetId]; if (element) { // Remove list entry from list - const list = element.list; - const listEntry = element.entry; + const list = element.list$; + const listEntry = element.entry$; if (list) { for (let i = 0, l = list.length; i < l; i++) { if (list[i] === listEntry) { @@ -1190,7 +1190,7 @@ export class Scheduler extends System { } } - delete this._hashForUpdates[targetId]; + delete this._hashForUpdates$[targetId]; if (listEntry) { ListEntry.put(listEntry); } @@ -1198,9 +1198,9 @@ export class Scheduler extends System { } } - private _priorityIn (ppList: ListEntry[], listElement: ListEntry, priority: number): void { + private _priorityIn$ (ppList: ListEntry[], listElement: ListEntry, priority: number): void { for (let i = 0; i < ppList.length; i++) { - if (priority < ppList[i].priority) { + if (priority < ppList[i].priority$) { ppList.splice(i, 0, listElement); return; } @@ -1208,7 +1208,7 @@ export class Scheduler extends System { ppList.push(listElement); } - private _appendIn (ppList: ListEntry[], listElement: ListEntry): void { + private _appendIn$ (ppList: ListEntry[], listElement: ListEntry): void { ppList.push(listElement); } } diff --git a/cocos/core/settings.ts b/cocos/core/settings.ts index 10a7afb9f32..5bd293eb4e6 100644 --- a/cocos/core/settings.ts +++ b/cocos/core/settings.ts @@ -34,7 +34,7 @@ declare const require: (path: string) => Promise; * @en * The default grouping in Settings, which usually corresponds to the module. */ -enum Category { +export enum SettingsCategory { PATH = 'path', ENGINE = 'engine', ASSETS = 'assets', @@ -59,7 +59,7 @@ enum Category { * You can access this single instance of the module via [settings]. */ export class Settings { - static Category = Category; + static Category = SettingsCategory; /** * Initialization @@ -83,7 +83,7 @@ export class Settings { // For now, we use a system module context to dynamically import the relative path of module. const settingsModule = '../settings.js'; import(settingsModule).then((res): void => { - this._settings = res.default; + this._settings$ = res.default; resolve(); }).catch((e): void => reject(e)); }); @@ -98,7 +98,7 @@ export class Settings { reject(err); return; } - this._settings = result; + this._settings$ = result; resolve(); }); } else { @@ -106,7 +106,7 @@ export class Settings { if (result instanceof Error) { reject(result); } else { - this._settings = result; + this._settings$ = result; resolve(); } } @@ -115,7 +115,7 @@ export class Settings { xhr.open('GET', path); xhr.responseType = 'text'; xhr.onload = (): void => { - this._settings = JSON.parse(xhr.response); + this._settings$ = JSON.parse(xhr.response as string); resolve(); }; xhr.onerror = (): void => { @@ -139,16 +139,16 @@ export class Settings { * * @example * ```ts - * console.log(settings.querySettings(Settings.Category.ASSETS, 'server')); // print https://www.cocos.com - * settings.overrideSettings(Settings.Category.ASSETS, 'server', 'http://www.test.com'); - * console.log(settings.querySettings(Settings.Category.ASSETS, 'server')); // print http://www.test.com + * console.log(settings.querySettings(SettingsCategory.ASSETS, 'server')); // print https://www.cocos.com + * settings.overrideSettings(SettingsCategory.ASSETS, 'server', 'http://www.test.com'); + * console.log(settings.querySettings(SettingsCategory.ASSETS, 'server')); // print http://www.test.com * ``` */ - overrideSettings (category: Category | string, name: string, value: T): void { - if (!(category in this._override)) { - this._override[category] = {}; + overrideSettings (category: SettingsCategory | string, name: string, value: T): void { + if (!(category in this._override$)) { + this._override$[category] = {}; } - this._override[category][name] = value; + this._override$[category][name] = value; } /** @@ -164,18 +164,18 @@ export class Settings { * * @example * ```ts - * console.log(settings.querySettings(Settings.Category.ENGINE, 'debug')); // print false + * console.log(settings.querySettings(SettingsCategory.ENGINE, 'debug')); // print false * ``` */ - querySettings (category: Category | string, name: string): T | null { - if (category in this._override) { - const categorySettings = this._override[category]; + querySettings (category: SettingsCategory | string, name: string): T | null { + if (category in this._override$) { + const categorySettings = this._override$[category]; if (categorySettings && name in categorySettings) { return categorySettings[name] as T; } } - if (category in this._settings) { - const categorySettings = this._settings[category]; + if (category in this._settings$) { + const categorySettings = this._settings$[category]; if (categorySettings && name in categorySettings) { return categorySettings[name] as T; } @@ -183,12 +183,12 @@ export class Settings { return null; } - private _settings: Record = {}; - private _override: Record = {}; + private _settings$: Record = {}; + private _override$: Record = {}; } export declare namespace Settings { - export type Category = typeof Category; + export type Category = typeof SettingsCategory; } /** diff --git a/cocos/core/utils/pool.ts b/cocos/core/utils/pool.ts index 13cbc03c254..4ca9c07febc 100644 --- a/cocos/core/utils/pool.ts +++ b/cocos/core/utils/pool.ts @@ -98,8 +98,8 @@ export class Pool { return this._get(); } - private declare _pool: Array; - private declare _cleanup: CleanUpFunction | null; + private declare _pool$: Array; + private declare _cleanup$: CleanUpFunction | null; /** * @en Constructor. @zh 构造函数。 @@ -125,8 +125,8 @@ export class Pool { constructor (_0: CleanUpFunction | number, _1?: number) { const size = (_1 === undefined) ? (_0 as number) : _1; const cleanupFunc = (_1 === undefined) ? null : (_0 as CleanUpFunction); - this._pool = new Array(size); - this._cleanup = cleanupFunc; + this._pool$ = new Array(size); + this._cleanup$ = cleanupFunc; } /** @@ -140,8 +140,8 @@ export class Pool { public _get (): T | null { if (this.count > 0) { --this.count; - const cache = this._pool[this.count]; - this._pool[this.count] = null; + const cache = this._pool$[this.count]; + this._pool$[this.count] = null; return cache; } return null; @@ -152,9 +152,9 @@ export class Pool { * @zh 向对象池返还一个不再需要的对象。 */ public put (obj: T): void { - const pool = this._pool; + const pool = this._pool$; if (this.count < pool.length) { - if (this._cleanup && this._cleanup(obj) === false) { + if (this._cleanup$ && this._cleanup$(obj) === false) { return; } pool[this.count] = obj; @@ -170,7 +170,7 @@ export class Pool { */ public resize (length: number): void { if (length >= 0) { - this._pool.length = length; + this._pool$.length = length; if (this.count > length) { this.count = length; } diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index 3a301c02ff9..615b501c053 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -57,7 +57,7 @@ ccenum(DefaultAnimsEnum); enum DefaultCacheMode { REALTIME = 0, } -ccenum(DefaultAnimsEnum); +ccenum(DefaultCacheMode); /** * @en Control animation speed, should be larger than 0. diff --git a/cocos/dragon-bones/index.jsb.ts b/cocos/dragon-bones/index.jsb.ts index 15b6e632de5..f73c16286f2 100644 --- a/cocos/dragon-bones/index.jsb.ts +++ b/cocos/dragon-bones/index.jsb.ts @@ -40,7 +40,7 @@ export enum ExtensionType { * @engineInternal Since v3.7.2, this is an engine private enum type. * @deprecated Since v3.7.2, will be removed in the future. */ -export enum EventType { +export enum DragonBonesEventType { Frame = 0, Sound = 1 } diff --git a/cocos/dragon-bones/index.ts b/cocos/dragon-bones/index.ts index 86d1ae85903..de0e198065b 100644 --- a/cocos/dragon-bones/index.ts +++ b/cocos/dragon-bones/index.ts @@ -41,7 +41,7 @@ export enum ExtensionType { * @en Event type in dragonbones animation. * @zh 龙骨动画中的事件类型。 */ -export enum EventType { +export enum DragonBonesEventType { /** * @en Event about animation frame. * @zh 动画帧相关的事件。 diff --git a/cocos/game/director.ts b/cocos/game/director.ts index 42fcb8f0a62..3d97205c7ed 100644 --- a/cocos/game/director.ts +++ b/cocos/game/director.ts @@ -32,7 +32,7 @@ import { SceneAsset } from '../asset/assets/scene-asset'; import { System, EventTarget, Scheduler, js, errorID, error, assertID, warnID, macro, CCObject, cclegacy, isValid } from '../core'; import { input } from '../input'; import { Root } from '../root'; -import { Node, Scene } from '../scene-graph'; +import { Node, NodeEventType, Scene } from '../scene-graph'; import { ComponentScheduler } from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; import { scalableContainerManager } from '../core/memop/scalable-container'; @@ -43,6 +43,120 @@ import { releaseManager } from '../asset/asset-manager/release-manager'; // ---------------------------------------------------------------------------------------------------------------------- +export enum DirectorEvent { + /** + * @en The event which will be triggered when the singleton of Director initialized. + * @zh Director 单例初始化时触发的事件 + * @event INIT + */ + INIT = 'director_init', + + /** + * @en The event which will be triggered when the singleton of Director reset. + * @zh Director 单例重置时触发的事件 + * @event RESET + */ + RESET = 'director_reset', + + /** + * @en The event which will be triggered before loading a new scene. + * @zh 加载新场景之前所触发的事件。 + * @event BEFORE_SCENE_LOADING + */ + BEFORE_SCENE_LOADING = 'director_before_scene_loading', + + /** + * @en The event which will be triggered before launching a new scene. + * @zh 运行新场景之前所触发的事件。 + * @event BEFORE_SCENE_LAUNCH + */ + BEFORE_SCENE_LAUNCH = 'director_before_scene_launch', + + /** + * @en The event which will be triggered after launching a new scene. + * @zh 运行新场景之后所触发的事件。 + * @event AFTER_SCENE_LAUNCH + */ + AFTER_SCENE_LAUNCH = 'director_after_scene_launch', + + /** + * @en The event which will be triggered at the beginning of every frame. + * @zh 每个帧的开始时所触发的事件。 + * @event BEFORE_UPDATE + */ + BEFORE_UPDATE = 'director_before_update', + + /** + * @en The event which will be triggered after engine and components update logic. + * @zh 将在引擎和组件 “update” 逻辑之后所触发的事件。 + * @event AFTER_UPDATE + */ + AFTER_UPDATE = 'director_after_update', + + /** + * @en The event which will be triggered before the rendering process. + * @zh 渲染过程之前所触发的事件。 + * @event BEFORE_DRAW + */ + BEFORE_DRAW = 'director_before_draw', + + /** + * @en The event which will be triggered after the rendering process. + * @zh 渲染过程之后所触发的事件。 + * @event AFTER_DRAW + */ + AFTER_DRAW = 'director_after_draw', + + /** + * @en The event which will be triggered before the pipeline render commit. + * @zh 当前渲染帧提交前所触发的事件。 + * @event BEFORE_COMMIT + */ + BEFORE_COMMIT = 'director_before_commit', + + /** + * @en The event which will be triggered before the render pipeline processes the render scene. + * @zh 当前帧将渲染场景提交到渲染管线之前所触发的事件。 + * @event BEFORE_RENDER + */ + BEFORE_RENDER = 'director_before_render', + + /** + * @en The event which will be triggered after the render pipeline finishes the rendering process on CPU. + * @zh 当前帧渲染管线渲染流程完成后所触发的事件。 + * @event AFTER_RENDER + */ + AFTER_RENDER = 'director_after_render', + + /** + * @en The event which will be triggered before the physics process.
+ * @zh 物理过程之前所触发的事件。 + * @event BEFORE_PHYSICS + */ + BEFORE_PHYSICS = 'director_before_physics', + + /** + * @en The event which will be triggered after the physics process.
+ * @zh 物理过程之后所触发的事件。 + * @event AFTER_PHYSICS + */ + AFTER_PHYSICS = 'director_after_physics', + + /** + * @en The event which will be triggered at the frame begin.
+ * @zh 一帧开始时所触发的事件。 + * @event BEGIN_FRAME + */ + BEGIN_FRAME = 'director_begin_frame', + + /** + * @en The event which will be triggered at the frame end.
+ * @zh 一帧结束之后所触发的事件。 + * @event END_FRAME + */ + END_FRAME = 'director_end_frame', +} + /** * @en * ATTENTION: USE `director` INSTEAD OF `Director`. @@ -66,112 +180,112 @@ export class Director extends EventTarget { * @zh Director 单例初始化时触发的事件 * @event Director.EVENT_INIT */ - public static readonly EVENT_INIT = 'director_init'; + public static readonly EVENT_INIT = DirectorEvent.INIT; /** * @en The event which will be triggered when the singleton of Director reset. * @zh Director 单例重置时触发的事件 * @event Director.EVENT_RESET */ - public static readonly EVENT_RESET = 'director_reset'; + public static readonly EVENT_RESET = DirectorEvent.RESET; /** * @en The event which will be triggered before loading a new scene. * @zh 加载新场景之前所触发的事件。 * @event Director.EVENT_BEFORE_SCENE_LOADING */ - public static readonly EVENT_BEFORE_SCENE_LOADING = 'director_before_scene_loading'; + public static readonly EVENT_BEFORE_SCENE_LOADING = DirectorEvent.BEFORE_SCENE_LOADING; /** * @en The event which will be triggered before launching a new scene. * @zh 运行新场景之前所触发的事件。 * @event Director.EVENT_BEFORE_SCENE_LAUNCH */ - public static readonly EVENT_BEFORE_SCENE_LAUNCH = 'director_before_scene_launch'; + public static readonly EVENT_BEFORE_SCENE_LAUNCH = DirectorEvent.BEFORE_SCENE_LAUNCH; /** * @en The event which will be triggered after launching a new scene. * @zh 运行新场景之后所触发的事件。 * @event Director.EVENT_AFTER_SCENE_LAUNCH */ - public static readonly EVENT_AFTER_SCENE_LAUNCH = 'director_after_scene_launch'; + public static readonly EVENT_AFTER_SCENE_LAUNCH = DirectorEvent.AFTER_SCENE_LAUNCH; /** * @en The event which will be triggered at the beginning of every frame. * @zh 每个帧的开始时所触发的事件。 * @event Director.EVENT_BEFORE_UPDATE */ - public static readonly EVENT_BEFORE_UPDATE = 'director_before_update'; + public static readonly EVENT_BEFORE_UPDATE = DirectorEvent.BEFORE_UPDATE; /** * @en The event which will be triggered after engine and components update logic. * @zh 将在引擎和组件 “update” 逻辑之后所触发的事件。 * @event Director.EVENT_AFTER_UPDATE */ - public static readonly EVENT_AFTER_UPDATE = 'director_after_update'; + public static readonly EVENT_AFTER_UPDATE = DirectorEvent.AFTER_UPDATE; /** * @en The event which will be triggered before the rendering process. * @zh 渲染过程之前所触发的事件。 * @event Director.EVENT_BEFORE_DRAW */ - public static readonly EVENT_BEFORE_DRAW = 'director_before_draw'; + public static readonly EVENT_BEFORE_DRAW = DirectorEvent.BEFORE_DRAW; /** * @en The event which will be triggered after the rendering process. * @zh 渲染过程之后所触发的事件。 * @event Director.EVENT_AFTER_DRAW */ - public static readonly EVENT_AFTER_DRAW = 'director_after_draw'; + public static readonly EVENT_AFTER_DRAW = DirectorEvent.AFTER_DRAW; /** * @en The event which will be triggered before the pipeline render commit. * @zh 当前渲染帧提交前所触发的事件。 * @event Director.EVENT_BEFORE_COMMIT */ - public static readonly EVENT_BEFORE_COMMIT = 'director_before_commit'; + public static readonly EVENT_BEFORE_COMMIT = DirectorEvent.BEFORE_COMMIT; /** * @en The event which will be triggered before the render pipeline processes the render scene. * @zh 当前帧将渲染场景提交到渲染管线之前所触发的事件。 * @event Director.EVENT_BEFORE_RENDER */ - public static readonly EVENT_BEFORE_RENDER = 'director_before_render'; + public static readonly EVENT_BEFORE_RENDER = DirectorEvent.BEFORE_RENDER; /** * @en The event which will be triggered after the render pipeline finishes the rendering process on CPU. * @zh 当前帧渲染管线渲染流程完成后所触发的事件。 * @event Director.EVENT_AFTER_RENDER */ - public static readonly EVENT_AFTER_RENDER = 'director_after_render'; + public static readonly EVENT_AFTER_RENDER = DirectorEvent.AFTER_RENDER; /** * @en The event which will be triggered before the physics process.
* @zh 物理过程之前所触发的事件。 * @event Director.EVENT_BEFORE_PHYSICS */ - public static readonly EVENT_BEFORE_PHYSICS = 'director_before_physics'; + public static readonly EVENT_BEFORE_PHYSICS = DirectorEvent.BEFORE_PHYSICS; /** * @en The event which will be triggered after the physics process.
* @zh 物理过程之后所触发的事件。 * @event Director.EVENT_AFTER_PHYSICS */ - public static readonly EVENT_AFTER_PHYSICS = 'director_after_physics'; + public static readonly EVENT_AFTER_PHYSICS = DirectorEvent.AFTER_PHYSICS; /** * @en The event which will be triggered at the frame begin.
* @zh 一帧开始时所触发的事件。 * @event Director.EVENT_BEGIN_FRAME */ - public static readonly EVENT_BEGIN_FRAME = 'director_begin_frame'; + public static readonly EVENT_BEGIN_FRAME = DirectorEvent.BEGIN_FRAME; /** * @en The event which will be triggered at the frame end.
* @zh 一帧结束之后所触发的事件。 * @event Director.EVENT_END_FRAME */ - public static readonly EVENT_END_FRAME = 'director_end_frame'; + public static readonly EVENT_END_FRAME = DirectorEvent.END_FRAME; public static instance: Director; @@ -183,15 +297,15 @@ export class Director extends EventTarget { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _nodeActivator: NodeActivator = new NodeActivator(); - private _invalid: boolean = false; - private _paused: boolean = false; - private _root: Root | null = null; - private _loadingScene: string = ''; - private _scene: Scene | null = null; - private _totalFrames: number = 0; // FPS - private _scheduler: Scheduler = new Scheduler(); // Scheduler for user registration update - private _systems: System[] = []; - private _persistRootNodes: Record = {}; + private _invalid$: boolean = false; + private _paused$: boolean = false; + private _root$: Root | null = null; + private _loadingScene$: string = ''; + private _scene$: Scene | null = null; + private _totalFrames$: number = 0; // FPS + private _scheduler$: Scheduler = new Scheduler(); // Scheduler for user registration update + private _systems$: System[] = []; + private _persistRootNodes$: Record = {}; constructor () { super(); @@ -202,7 +316,7 @@ export class Director extends EventTarget { * @zh 执行完当前帧后停止 director 的执行 */ public end (): void { - this.once(Director.EVENT_END_FRAME, (): void => { + this.once(DirectorEvent.END_FRAME, (): void => { this.purgeDirector(); }); } @@ -216,7 +330,7 @@ export class Director extends EventTarget { * 如果想要更彻底得暂停游戏,包含渲染,音频和事件,请使用 `game.pause` 。 */ public pause (): void { - this._paused = true; + this._paused$ = true; } /** @@ -227,16 +341,16 @@ export class Director extends EventTarget { */ public purgeDirector (): void { // cleanup scheduler - this._scheduler.unscheduleAll(); + this._scheduler$.unscheduleAll(); this._compScheduler.unscheduleAll(); this._nodeActivator.reset(); if (!EDITOR) { - if (isValid(this._scene)) { - this._scene!.destroy(); + if (isValid(this._scene$)) { + this._scene$!.destroy(); } - this._scene = null; + this._scene$ = null; } this.stopAnimation(); @@ -252,14 +366,14 @@ export class Director extends EventTarget { public reset (): void { this.purgeDirector(); - for (const id in this._persistRootNodes) { - this.removePersistRootNode(this._persistRootNodes[id]); + for (const id in this._persistRootNodes$) { + this.removePersistRootNode(this._persistRootNodes$[id]); } // Clear scene this.getScene()?.destroy(); - this.emit(Director.EVENT_RESET); + this.emit(DirectorEvent.RESET); this.startAnimation(); } @@ -295,10 +409,10 @@ export class Director extends EventTarget { // eslint-disable-next-line no-console console.time('AttachPersist'); } - const persistNodeList = Object.keys(this._persistRootNodes).map((x): Node => this._persistRootNodes[x]); + const persistNodeList = Object.keys(this._persistRootNodes$).map((x): Node => this._persistRootNodes$[x]); for (let i = 0; i < persistNodeList.length; i++) { const node = persistNodeList[i]; - node.emit(Node.EventType.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene); + node.emit(NodeEventType.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene); const existNode = scene.uuid === node._originalSceneId && scene.getChildByUuid(node.uuid); if (existNode) { // scene also contains the persist node, select the old one @@ -317,7 +431,7 @@ export class Director extends EventTarget { // eslint-disable-next-line no-console console.timeEnd('AttachPersist'); } - const oldScene = this._scene; + const oldScene = this._scene$; // unload scene if (BUILD && DEBUG) { @@ -333,14 +447,14 @@ export class Director extends EventTarget { // eslint-disable-next-line no-console console.time('AutoRelease'); } - releaseManager._autoRelease(oldScene!, scene, this._persistRootNodes); + releaseManager._autoRelease(oldScene!, scene, this._persistRootNodes$); if (BUILD && DEBUG) { // eslint-disable-next-line no-console console.timeEnd('AutoRelease'); } } - this._scene = null; + this._scene$ = null; // purge destroyed nodes belongs to old scene CCObject._deferredDestroy(); @@ -350,10 +464,10 @@ export class Director extends EventTarget { if (onBeforeLoadScene) { onBeforeLoadScene(); } - this.emit(Director.EVENT_BEFORE_SCENE_LAUNCH, scene); + this.emit(DirectorEvent.BEFORE_SCENE_LAUNCH, scene); // Run an Entity Scene - this._scene = scene; + this._scene$ = scene; if (BUILD && DEBUG) { // eslint-disable-next-line no-console @@ -365,14 +479,14 @@ export class Director extends EventTarget { console.timeEnd('Activate'); } // start scene - if (this._root) { - this._root.resetCumulativeTime(); + if (this._root$) { + this._root$.resetCumulativeTime(); } this.startAnimation(); if (onLaunched) { onLaunched(null, scene); } - this.emit(Director.EVENT_AFTER_SCENE_LAUNCH, scene); + this.emit(DirectorEvent.AFTER_SCENE_LAUNCH, scene); } /** @@ -391,7 +505,7 @@ export class Director extends EventTarget { assertID(scene instanceof Scene, 1216); // Delay run / replace scene to the end of the frame - this.once(Director.EVENT_END_FRAME, (): void => { + this.once(DirectorEvent.END_FRAME, (): void => { this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched); }); } @@ -405,20 +519,20 @@ export class Director extends EventTarget { * @return if error, return false */ public loadScene (sceneName: string, onLaunched?: Director.OnSceneLaunched, onUnloaded?: Director.OnUnload): boolean { - if (this._loadingScene) { - warnID(1208, sceneName, this._loadingScene); + if (this._loadingScene$) { + warnID(1208, sceneName, this._loadingScene$); return false; } const bundle = assetManager.bundles.find((bundle): boolean => !!bundle.getSceneInfo(sceneName)); if (bundle) { - this.emit(Director.EVENT_BEFORE_SCENE_LOADING, sceneName); - this._loadingScene = sceneName; + this.emit(DirectorEvent.BEFORE_SCENE_LOADING, sceneName); + this._loadingScene$ = sceneName; // eslint-disable-next-line no-console console.time(`LoadScene ${sceneName}`); bundle.loadScene(sceneName, (err, scene): void => { // eslint-disable-next-line no-console console.timeEnd(`LoadScene ${sceneName}`); - this._loadingScene = ''; + this._loadingScene$ = ''; if (err) { error(err); if (onLaunched) { @@ -492,11 +606,11 @@ export class Director extends EventTarget { * @zh 恢复暂停场景的游戏逻辑,如果当前场景没有暂停将没任何事情发生。 */ public resume (): void { - this._paused = false; + this._paused$ = false; } get root (): Root | null { - return this._root; + return this._root$; } /** @@ -510,7 +624,7 @@ export class Director extends EventTarget { * ``` */ public getScene (): Scene | null { - return this._scene; + return this._scene$; } /** @@ -545,7 +659,7 @@ export class Director extends EventTarget { * @zh 获取 director 启动以来游戏运行的总帧数。 */ public getTotalFrames (): number { - return this._totalFrames; + return this._totalFrames$; } /** @@ -553,7 +667,7 @@ export class Director extends EventTarget { * @zh 是否处于暂停状态。 */ public isPaused (): boolean { - return this._paused; + return this._paused$; } /** @@ -561,7 +675,7 @@ export class Director extends EventTarget { * @zh 获取和 director 相关联的调度器。 */ public getScheduler (): Scheduler { - return this._scheduler; + return this._scheduler$; } /** @@ -569,9 +683,9 @@ export class Director extends EventTarget { * @zh 设置和 director 相关联的调度器。 */ public setScheduler (scheduler: Scheduler): void { - if (this._scheduler !== scheduler) { - this.unregisterSystem(this._scheduler); - this._scheduler = scheduler; + if (this._scheduler$ !== scheduler) { + this.unregisterSystem(this._scheduler$); + this._scheduler$ = scheduler; this.registerSystem(Scheduler.ID, scheduler, 200); } } @@ -583,13 +697,13 @@ export class Director extends EventTarget { public registerSystem (name: string, sys: System, priority: number): void { sys.id = name; sys.priority = priority; - this._systems.push(sys); - this._systems.sort(System.sortByPriority); + this._systems$.push(sys); + this._systems$.sort(System.sortByPriority); } public unregisterSystem (sys: System): void { - js.array.fastRemove(this._systems, sys); - this._systems.sort(System.sortByPriority); + js.array.fastRemove(this._systems$, sys); + this._systems$.sort(System.sortByPriority); } /** @@ -597,7 +711,7 @@ export class Director extends EventTarget { * @zh 获取一个 system。 */ public getSystem (name: string): System | undefined { - return this._systems.find((sys): boolean => sys.id === name); + return this._systems$.find((sys): boolean => sys.id === name); } /** @@ -615,7 +729,7 @@ export class Director extends EventTarget { * @zh 开始执行游戏逻辑 */ public startAnimation (): void { - this._invalid = false; + this._invalid$ = false; } /** @@ -623,7 +737,7 @@ export class Director extends EventTarget { * @zh 停止执行游戏逻辑,每帧渲染会继续执行 */ public stopAnimation (): void { - this._invalid = true; + this._invalid$ = true; } /** @@ -647,46 +761,46 @@ export class Director extends EventTarget { * @param dt Delta time in seconds */ public tick (dt: number): void { - if (!this._invalid) { - this.emit(Director.EVENT_BEGIN_FRAME); + if (!this._invalid$) { + this.emit(DirectorEvent.BEGIN_FRAME); if (!EDITOR_NOT_IN_PREVIEW) { input._frameDispatchEvents(); } // Update - if (!this._paused) { - this.emit(Director.EVENT_BEFORE_UPDATE); + if (!this._paused$) { + this.emit(DirectorEvent.BEFORE_UPDATE); // Call start for new added components this._compScheduler.startPhase(); // Update for components this._compScheduler.updatePhase(dt); // Update systems - for (let i = 0; i < this._systems.length; ++i) { - this._systems[i].update(dt); + for (let i = 0; i < this._systems$.length; ++i) { + this._systems$[i].update(dt); } // Late update for components this._compScheduler.lateUpdatePhase(dt); // User can use this event to do things after update - this.emit(Director.EVENT_AFTER_UPDATE); + this.emit(DirectorEvent.AFTER_UPDATE); // Destroy entities that have been removed recently CCObject._deferredDestroy(); // Post update systems - for (let i = 0; i < this._systems.length; ++i) { - this._systems[i].postUpdate(dt); + for (let i = 0; i < this._systems$.length; ++i) { + this._systems$[i].postUpdate(dt); } } - this.emit(Director.EVENT_BEFORE_DRAW); + this.emit(DirectorEvent.BEFORE_DRAW); uiRendererManager.updateAllDirtyRenderers(); - this._root!.frameMove(dt); - this.emit(Director.EVENT_AFTER_DRAW); + this._root$!.frameMove(dt); + this.emit(DirectorEvent.AFTER_DRAW); Node.resetHasChangedFlags(); Node.clearNodeArray(); scalableContainerManager.update(dt); - this.emit(Director.EVENT_END_FRAME); - this._totalFrames++; + this.emit(DirectorEvent.END_FRAME); + this._totalFrames$++; } } @@ -695,12 +809,12 @@ export class Director extends EventTarget { * @zh 构建自定义渲染管线 */ private buildRenderPipeline (): void { - if (!this._root) { + if (!this._root$) { return; } // Here we should build the render pipeline. - const ppl = this._root.customPipeline; - const cameras = this._root.cameraList; + const ppl = this._root$.customPipeline; + const cameras = this._root$.cameraList; ppl.beginSetup(); const builder = cclegacy.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME); @@ -715,14 +829,14 @@ export class Director extends EventTarget { // (in CocosCreator/Project/Project Settings/Engine Manager/Macro Configuration/CUSTOM_PIPELINE_NAME) // 2. cclegacy.rendering is available // 3. The root node is created and uses custom pipeline - if (macro.CUSTOM_PIPELINE_NAME !== '' && cclegacy.rendering && this._root && this._root.usesCustomPipeline) { + if (macro.CUSTOM_PIPELINE_NAME !== '' && cclegacy.rendering && this._root$ && this._root$.usesCustomPipeline) { this.on( - Director.EVENT_BEFORE_RENDER, + DirectorEvent.BEFORE_RENDER, this.buildRenderPipeline, this, ); this.on( - Director.EVENT_BEFORE_SCENE_LAUNCH, + DirectorEvent.BEFORE_SCENE_LAUNCH, cclegacy.rendering.forceResizeAllWindows, cclegacy.rendering, ); @@ -733,22 +847,22 @@ export class Director extends EventTarget { * @internal */ public init (): void { - this._totalFrames = 0; - this._paused = false; + this._totalFrames$ = 0; + this._paused$ = false; // Scheduler // TODO: have a solid organization of priority and expose to user - this.registerSystem(Scheduler.ID, this._scheduler, 200); - this._root = new Root(deviceManager.gfxDevice); + this.registerSystem(Scheduler.ID, this._scheduler$, 200); + this._root$ = new Root(deviceManager.gfxDevice); const rootInfo = {}; - this._root.initialize(rootInfo); + this._root$.initialize(rootInfo); this.setupRenderPipelineBuilder(); - for (let i = 0; i < this._systems.length; i++) { - this._systems[i].init(); + for (let i = 0; i < this._systems$.length; i++) { + this._systems$[i].init(); } - this.emit(Director.EVENT_INIT); + this.emit(DirectorEvent.INIT); } // @ Persist root node section @@ -767,8 +881,8 @@ export class Director extends EventTarget { return; } const id = node.uuid; - if (!this._persistRootNodes[id]) { - const scene = this._scene as any; + if (!this._persistRootNodes$[id]) { + const scene = this._scene$ as any; if (isValid(scene)) { if (!node.parent) { node.parent = scene; @@ -783,7 +897,7 @@ export class Director extends EventTarget { node._originalSceneId = scene.uuid; } } - this._persistRootNodes[id] = node; + this._persistRootNodes$[id] = node; node._persistNode = true; releaseManager._addPersistNodeRef(node); } @@ -796,8 +910,8 @@ export class Director extends EventTarget { */ public removePersistRootNode (node: Node): void { const id = node.uuid || ''; - if (node === this._persistRootNodes[id]) { - delete this._persistRootNodes[id]; + if (node === this._persistRootNodes$[id]) { + delete this._persistRootNodes$[id]; node._persistNode = false; node._originalSceneId = ''; releaseManager._removePersistNodeRef(node); diff --git a/cocos/game/game.ts b/cocos/game/game.ts index 0b856a69e20..a68a24950d7 100644 --- a/cocos/game/game.ts +++ b/cocos/game/game.ts @@ -23,20 +23,22 @@ THE SOFTWARE. */ -import { DEBUG, EDITOR, NATIVE, PREVIEW, TEST, EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; +import { DEBUG, EDITOR, NATIVE, PREVIEW, TEST, EDITOR_NOT_IN_PREVIEW, WECHAT } from 'internal:constants'; import { systemInfo } from 'pal/system-info'; import { findCanvas, loadJsFile } from 'pal/env'; import { Pacer } from 'pal/pacer'; import { ConfigOrientation } from 'pal/screen-adapter'; import assetManager, { IAssetManagerOptions } from '../asset/asset-manager/asset-manager'; -import { EventTarget, AsyncDelegate, sys, macro, VERSION, cclegacy, screen, Settings, settings, - assert, garbageCollectionManager, DebugMode, warn, log, _resetDebugSetting, errorID, logID } from '../core'; +import { EventTarget, AsyncDelegate, sys, macro, VERSION, cclegacy, screen, settings, + assert, garbageCollectionManager, DebugMode, warn, log, _resetDebugSetting, errorID, logID, + SettingsCategory, + Settings } from '../core'; import { input } from '../input'; import { deviceManager, LegacyRenderMode } from '../gfx'; import { SplashScreen } from './splash-screen'; import { Layers, Node } from '../scene-graph'; import { builtinResMgr } from '../asset/asset-manager/builtin-res-mgr'; -import { Director, director } from './director'; +import { director, DirectorEvent } from './director'; import { bindingMappingInfo } from '../rendering/define'; import { ICustomJointTextureLayout } from '../3d/skeletal-animation/skeletal-animation-utils'; import { IPhysicsConfig } from '../physics/framework/physics-config'; @@ -88,7 +90,7 @@ export interface IGameConfig { * 当 showFPS 为 true 的时候界面的左下角将显示 fps 的信息,否则被隐藏。 * @en * Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.PROFILING: { "showFPS": true }}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.PROFILING: { "showFPS": true }}``` to set this. */ showFPS?: boolean; @@ -97,7 +99,7 @@ export interface IGameConfig { * 设置想要的帧率你的游戏,但真正的FPS取决于你的游戏实现和运行环境。 * @en * Set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment. - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.SCREEN: { "frameRate": 60 }}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.SCREEN: { "frameRate": 60 }}``` to set this. */ frameRate?: number; @@ -117,7 +119,7 @@ export interface IGameConfig { * - 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers. * - 3 - Use Headless Renderer, which is useful in test or server env, only for internal use by cocos team for now * - 4 - Force WebGPU rendering, but this option will be ignored in some browsers. - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.RENDERING: { "renderMode": 0 }}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.RENDERING: { "renderMode": 0 }}``` to set this. */ renderMode?: 0 | 1 | 2 | 3 | 4; @@ -126,7 +128,7 @@ export interface IGameConfig { * Render pipeline resources * @zh * Render pipeline 资源 - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.RENDERING: { "renderPipeline": '' }}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.RENDERING: { "renderPipeline": '' }}``` to set this. */ renderPipeline?: string; @@ -135,7 +137,7 @@ export interface IGameConfig { * Asset Manager initialization options * @zh * 资源管理器初始化设置 - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.ASSETS: {}}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.ASSETS: {}}``` to set this. */ assetOptions?: IAssetManagerOptions; @@ -144,7 +146,7 @@ export interface IGameConfig { * GPU instancing options * @zh * GPU instancing 选项 - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.ANIMATION: { customJointTextureLayouts: [] }}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.ANIMATION: { customJointTextureLayouts: [] }}``` to set this. */ customJointTextureLayouts?: ICustomJointTextureLayout[]; @@ -153,7 +155,7 @@ export interface IGameConfig { * Physics system config * @zh * 物理系统设置 - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.PHYSICS: {}}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.PHYSICS: {}}``` to set this. */ physics?: IPhysicsConfig; @@ -163,7 +165,7 @@ export interface IGameConfig { * Available value can be 'auto', 'landscape', 'portrait'. * @zh * 屏幕旋转方向,可选 “自动”,“横屏”,“竖屏” - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.SCREEN: { 'orientation': 'auto' }}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.SCREEN: { 'orientation': 'auto' }}``` to set this. */ orientation?: ConfigOrientation; @@ -173,7 +175,7 @@ export interface IGameConfig { * Now it only works on Web platform. * @zh * 是否让游戏外框对齐到屏幕上,目前只在 web 平台生效 - * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.SCREEN: { 'exactFitScreen': true }}``` to set this. + * @deprecated Since v3.6, Please use ```overrideSettings: { SettingsCategory.SCREEN: { 'exactFitScreen': true }}``` to set this. */ exactFitScreen?: boolean, } @@ -398,7 +400,7 @@ export class Game extends EventTarget { * @zh 引擎和渲染器是否以完成初始化 */ public get inited (): boolean { - return this._inited; + return this._inited$; } /** @@ -406,7 +408,7 @@ export class Game extends EventTarget { * @zh 游戏的设定帧率。 */ public get frameRate (): string | number { - return this._frameRate; + return this._frameRate$; } public set frameRate (frameRate: number | string) { if (typeof frameRate !== 'number') { @@ -415,9 +417,9 @@ export class Game extends EventTarget { frameRate = 60; } } - this._frameRate = frameRate; + this._frameRate$ = frameRate; this.frameTime = 1000 / frameRate; - if (this._pacer) this._pacer.targetFrameRate = this._frameRate; + if (this._pacer$) this._pacer$.targetFrameRate = this._frameRate$; } /** @@ -425,7 +427,7 @@ export class Game extends EventTarget { * @zh 获取上一帧的增量时间,以秒为单位。 */ public get deltaTime (): number { - return this._useFixedDeltaTime ? this.frameTime / 1000 : this._deltaTime; + return this._useFixedDeltaTime$ ? this.frameTime / 1000 : this._deltaTime$; } /** @@ -433,7 +435,7 @@ export class Game extends EventTarget { * @zh 获取从游戏开始到现在总共经过的时间,以毫秒为单位 */ public get totalTime (): number { - return performance.now() - this._initTime; + return performance.now() - this._initTime$; } /** @@ -441,7 +443,7 @@ export class Game extends EventTarget { * @zh 获取当前帧开始的时间(以 ms 为单位)。 */ public get frameStartTime (): number { - return this._startTime; + return this._startTime$; } /** @@ -455,19 +457,19 @@ export class Game extends EventTarget { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _isCloning = false; // deserializing or instantiating - private _inited = false; - private _engineInited = false; // whether the engine has inited - private _rendererInitialized = false; - private _paused = true; - private _pausedByEngine = false; + private _inited$ = false; + private _engineInited$ = false; // whether the engine has inited + private _rendererInitialized$ = false; + private _paused$ = true; + private _pausedByEngine$ = false; // frame control - private _frameRate = 60; - private _pacer: Pacer | null = null; - private _initTime = 0; - private _startTime = 0; - private _deltaTime = 0.0; - private _useFixedDeltaTime = false; - private _shouldLoadLaunchScene = true; + private _frameRate$ = 60; + private _pacer$: Pacer | null = null; + private _initTime$ = 0; + private _startTime$ = 0; + private _deltaTime$ = 0.0; + private _useFixedDeltaTime$ = false; + private _shouldLoadLaunchScene$ = true; /** * @en The event delegate pre base module initialization. At this point you can not use pal/logging/sys/settings API. @@ -551,9 +553,9 @@ export class Game extends EventTarget { * @en Called by the engine to pause the game. * @zh 提供给引擎调用暂停游戏接口。 */ - private pauseByEngine (): void { - if (this._paused) { return; } - this._pausedByEngine = true; + private pauseByEngine$ (): void { + if (this._paused$) { return; } + this._pausedByEngine$ = true; this.pause(); } @@ -561,10 +563,10 @@ export class Game extends EventTarget { * @en Resume paused game by engine call. * @zh 提供给引擎调用恢复暂停游戏接口。 */ - private resumeByEngine (): void { - if (this._pausedByEngine) { + private resumeByEngine$ (): void { + if (this._pausedByEngine$) { this.resume(); - this._pausedByEngine = false; + this._pausedByEngine$ = false; } } @@ -584,9 +586,9 @@ export class Game extends EventTarget { * 这点和只暂停游戏逻辑的 `director.pause()` 不同。 */ public pause (): void { - if (this._paused) { return; } - this._paused = true; - this._pacer?.stop(); + if (this._paused$) { return; } + this._paused$ = true; + this._pacer$?.stop(); this.emit(Game.EVENT_PAUSE); } @@ -596,10 +598,10 @@ export class Game extends EventTarget { * @zh 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。 */ public resume (): void { - if (!this._paused) { return; } + if (!this._paused$) { return; } input._clearEvents(); - this._paused = false; - this._pacer?.start(); + this._paused$ = false; + this._pacer$?.start(); this.emit(Game.EVENT_RESUME); } @@ -608,7 +610,7 @@ export class Game extends EventTarget { * @zh 判断游戏是否暂停。 */ public isPaused (): boolean { - return this._paused; + return this._paused$; } /** @@ -616,15 +618,23 @@ export class Game extends EventTarget { * @zh 重新开始游戏 */ public restart (): Promise { - const endFramePromise = new Promise((resolve): void => { director.once(Director.EVENT_END_FRAME, (): void => resolve()); }); + const endFramePromise = new Promise((resolve): void => { + director.once(DirectorEvent.END_FRAME, (): void => resolve()); + }); return endFramePromise.then((): void => { director.reset(); cclegacy.Object._deferredDestroy(); this.pause(); this.resume(); - this._shouldLoadLaunchScene = true; - SplashScreen.instance.curTime = 0; - this._safeEmit(Game.EVENT_RESTART); + this._shouldLoadLaunchScene$ = true; + }).then((): Promise => { + if (WECHAT) { + return Promise.resolve([]); + } else { + return SplashScreen.createInstance().init(); + } + }).then((): void => { + this._safeEmit$(Game.EVENT_RESTART); }); } @@ -652,7 +662,7 @@ export class Game extends EventTarget { */ public on (type: string, callback: () => void, target?: any, once?: boolean): any { // Make sure EVENT_ENGINE_INITED callbacks to be invoked - if (this.canRegisterEvent(type)) { + if (this.canRegisterEvent$(type)) { callback.call(target); } return this.eventTargetOn(type, callback, target, once); @@ -672,16 +682,16 @@ export class Game extends EventTarget { */ public once (type: string, callback: () => void, target?: any): any { // Make sure EVENT_ENGINE_INITED callbacks to be invoked - if (this.canRegisterEvent(type)) { + if (this.canRegisterEvent$(type)) { return callback.call(target); } return this.eventTargetOnce(type, callback, target); } - private canRegisterEvent (type: string): boolean { - return this._engineInited && type === Game.EVENT_ENGINE_INITED - || this._inited && type === Game.EVENT_GAME_INITED - || this._rendererInitialized && type === Game.EVENT_RENDERER_INITED; + private canRegisterEvent$ (type: string): boolean { + return this._engineInited$ && type === Game.EVENT_ENGINE_INITED + || this._inited$ && type === Game.EVENT_GAME_INITED + || this._rendererInitialized$ && type === Game.EVENT_RENDERER_INITED; } /** @@ -719,7 +729,7 @@ export class Game extends EventTarget { * @param config - Pass configuration object */ public init (config: IGameConfig): Promise { - this._compatibleWithOldParams(config); + this._compatibleWithOldParams$(config); // DONT change the order unless you know what's you doing return Promise.resolve() // #region Base @@ -737,7 +747,7 @@ export class Game extends EventTarget { }) .then((): Promise => sys.init()) .then((): void => { - this._initEvents(); + this._initEvents$(); }) .then((): Promise => settings.init(config.settingsPath, config.overrideSettings)) .then((): Promise => { @@ -761,7 +771,7 @@ export class Game extends EventTarget { console.time('Init Infrastructure'); } macro.init(); - this._initXR(); + this._initXR$(); const adapter = findCanvas(); if (adapter) { this.canvas = adapter.canvas; @@ -774,7 +784,7 @@ export class Game extends EventTarget { }) .then(() => { const usesCustomPipeline = settings.querySettings( - Settings.Category.RENDERING, + SettingsCategory.RENDERING, 'customPipeline', ); if (usesCustomPipeline) { @@ -793,7 +803,7 @@ export class Game extends EventTarget { assetManager.init(); builtinResMgr.init(); Layers.init(); - this.initPacer(); + this.initPacer$(); if (DEBUG) { // eslint-disable-next-line no-console console.timeEnd('Init Infrastructure'); @@ -809,13 +819,13 @@ export class Game extends EventTarget { this.emit(Game.EVENT_PRE_SUBSYSTEM_INIT); return this.onPreSubsystemInitDelegate.dispatch(); }) - .then((): Promise => effectSettings.init(settings.querySettings(Settings.Category.RENDERING, 'effectSettingsPath') as string)) + .then((): Promise => effectSettings.init(settings.querySettings(SettingsCategory.RENDERING, 'effectSettingsPath') as string)) .then((): void => { // initialize custom render pipeline if (!cclegacy.rendering || !cclegacy.rendering.enableEffectImport) { return; } - const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode'); + const renderMode = settings.querySettings(SettingsCategory.RENDERING, 'renderMode'); if (renderMode === LegacyRenderMode.HEADLESS) { cclegacy.rendering.init(deviceManager.gfxDevice, null); return; @@ -828,7 +838,7 @@ export class Game extends EventTarget { cclegacy.rendering.init(deviceManager.gfxDevice, data); }) .then((): Promise => { - const scriptPackages = settings.querySettings(Settings.Category.SCRIPTING, 'scriptPackages'); + const scriptPackages = settings.querySettings(SettingsCategory.SCRIPTING, 'scriptPackages'); if (scriptPackages) { return Promise.all(scriptPackages.map((pack): Promise => import(pack))); } @@ -853,7 +863,7 @@ export class Game extends EventTarget { .then((): void => { log(`Cocos Creator v${VERSION}`); this.emit(Game.EVENT_ENGINE_INITED); - this._engineInited = true; + this._engineInited$ = true; }) // #endregion Subsystem // #region Project @@ -866,7 +876,7 @@ export class Game extends EventTarget { // eslint-disable-next-line no-console console.time('Init Project'); } - const jsList = settings.querySettings(Settings.Category.PLUGINS, 'jsList'); + const jsList = settings.querySettings(SettingsCategory.PLUGINS, 'jsList'); let promise = Promise.resolve(); if (jsList) { jsList.forEach((jsListFile): void => { @@ -876,12 +886,15 @@ export class Game extends EventTarget { return promise; }) .then((): Promise => this._loadProjectBundles()) - .then((): Promise => this._loadCCEScripts()) - .then((): void | Promise => this._setupRenderPipeline()) - .then((): Promise => this._loadPreloadAssets()) + .then((): Promise => this._loadCCEScripts$()) + .then((): void | Promise => this._setupRenderPipeline$()) + .then((): Promise => this._loadPreloadAssets$()) .then((): Promise => { builtinResMgr.compileBuiltinMaterial(); - return SplashScreen.instance.init(); + if (WECHAT) { + return Promise.resolve([]); + } + return SplashScreen.createInstance().init(); }) .then((): Promise => { if (DEBUG) { @@ -893,30 +906,30 @@ export class Game extends EventTarget { }) // #endregion Project .then((): void => { - this._inited = true; - this._safeEmit(Game.EVENT_GAME_INITED); + this._inited$ = true; + this._safeEmit$(Game.EVENT_GAME_INITED); }); } - private _initXR (): void { + private _initXR$ (): void { if (typeof globalThis.__globalXR === 'undefined') { globalThis.__globalXR = {}; } const globalXR = globalThis.__globalXR; - globalXR.webxrCompatible = settings.querySettings(Settings.Category.XR, 'webxrCompatible') ?? false; + globalXR.webxrCompatible = settings.querySettings(SettingsCategory.XR, 'webxrCompatible') ?? false; if (sys.isXR) { // XrEntry must not be destroyed xr.entry = xr.XrEntry.getInstance(); - const xrMSAA = settings.querySettings(Settings.Category.RENDERING, 'msaa') ?? 1; - const xrRenderingScale = settings.querySettings(Settings.Category.RENDERING, 'renderingScale') ?? 1.0; + const xrMSAA = settings.querySettings(SettingsCategory.RENDERING, 'msaa') ?? 1; + const xrRenderingScale = settings.querySettings(SettingsCategory.RENDERING, 'renderingScale') ?? 1.0; xr.entry.setMultisamplesRTT(xrMSAA); xr.entry.setRenderingScale(xrRenderingScale); } } - private _compatibleWithOldParams (config: IGameConfig): void { + private _compatibleWithOldParams$ (config: IGameConfig): void { const overrideSettings = config.overrideSettings = config.overrideSettings || {}; if ('showFPS' in config) { overrideSettings.profiling = overrideSettings.profiling || {}; @@ -956,8 +969,8 @@ export class Game extends EventTarget { } } - private _loadPreloadAssets (): Promise { - const preloadAssets = settings.querySettings(Settings.Category.ASSETS, 'preloadAssets'); + private _loadPreloadAssets$ (): Promise { + const preloadAssets = settings.querySettings(SettingsCategory.ASSETS, 'preloadAssets'); if (!preloadAssets) return Promise.resolve([]); return Promise.all(preloadAssets.map((uuid): Promise => new Promise((resolve, reject): void => { assetManager.loadAny(uuid, (err): void => { @@ -973,7 +986,7 @@ export class Game extends EventTarget { /** * @internal only for browser preview */ - private _loadCCEScripts (): Promise { + private _loadCCEScripts$ (): Promise { return new Promise((resolve, reject): void => { // Since there is no script in the bundle during preview, we need to load the user's script in the following way if (PREVIEW && !TEST && !EDITOR && !NATIVE) { @@ -989,7 +1002,7 @@ export class Game extends EventTarget { * @internal only for game-view */ public _loadProjectBundles (): Promise { - const preloadBundles = settings.querySettings<{ bundle: string, version: string }[]>(Settings.Category.ASSETS, 'preloadBundles'); + const preloadBundles = settings.querySettings<{ bundle: string, version: string }[]>(SettingsCategory.ASSETS, 'preloadBundles'); if (!preloadBundles) return Promise.resolve([]); return Promise.all(preloadBundles.map(({ bundle, version }): Promise => new Promise((resolve, reject): void => { const opts: Record = {}; @@ -1013,7 +1026,7 @@ export class Game extends EventTarget { if (onStart) { this.onStart = onStart; } - if (!this._inited || EDITOR_NOT_IN_PREVIEW) { + if (!this._inited$ || EDITOR_NOT_IN_PREVIEW) { return; } this.resume(); @@ -1022,39 +1035,42 @@ export class Game extends EventTarget { // @Methods private _calculateDT (useFixedDeltaTime: boolean): number { - this._useFixedDeltaTime = useFixedDeltaTime; + this._useFixedDeltaTime$ = useFixedDeltaTime; if (useFixedDeltaTime) { - this._startTime = performance.now(); + this._startTime$ = performance.now(); return this.frameTime / 1000; } const now = performance.now(); - this._deltaTime = now > this._startTime ? (now - this._startTime) / 1000 : 0; - if (this._deltaTime > Game.DEBUG_DT_THRESHOLD) { - this._deltaTime = this.frameTime / 1000; + this._deltaTime$ = now > this._startTime$ ? (now - this._startTime$) / 1000 : 0; + if (this._deltaTime$ > Game.DEBUG_DT_THRESHOLD) { + this._deltaTime$ = this.frameTime / 1000; } - this._startTime = now; - return this._deltaTime; + this._startTime$ = now; + return this._deltaTime$; } - private _updateCallback (): void { - if (!this._inited) return; - if (!SplashScreen.instance.isFinished) { + private _updateCallback$ (): void { + if (!this._inited$) return; + if (!WECHAT && SplashScreen.instance && !SplashScreen.instance.isFinished) { SplashScreen.instance.update(this._calculateDT(false)); - } else if (this._shouldLoadLaunchScene) { - this._shouldLoadLaunchScene = false; - const launchScene = settings.querySettings(Settings.Category.LAUNCH, 'launchScene') as string; + } else if (this._shouldLoadLaunchScene$) { + if (!WECHAT) { + SplashScreen.releaseInstance(); + } + this._shouldLoadLaunchScene$ = false; + const launchScene = settings.querySettings(SettingsCategory.LAUNCH, 'launchScene') as string; if (launchScene) { // load scene director.loadScene(launchScene, (): void => { logID(1103, launchScene); - this._initTime = performance.now(); + this._initTime$ = performance.now(); director.startAnimation(); this.onStart?.(); }); } else { - this._initTime = performance.now(); + this._initTime$ = performance.now(); director.startAnimation(); this.onStart?.(); } @@ -1063,31 +1079,31 @@ export class Game extends EventTarget { } } - private initPacer (): void { - const frameRate = settings.querySettings(Settings.Category.SCREEN, 'frameRate') ?? 60; + private initPacer$ (): void { + const frameRate = settings.querySettings(SettingsCategory.SCREEN, 'frameRate') ?? 60; assert(typeof frameRate === 'number'); - this._pacer = new Pacer(); - this._pacer.onTick = this._updateCallback.bind(this); + this._pacer$ = new Pacer(); + this._pacer$.onTick = this._updateCallback$.bind(this); this.frameRate = frameRate; } - private _initEvents (): void { - systemInfo.on('show', this._onShow, this); - systemInfo.on('hide', this._onHide, this); - systemInfo.on('close', this._onClose, this); + private _initEvents$ (): void { + systemInfo.on('show', this._onShow$, this); + systemInfo.on('hide', this._onHide$, this); + systemInfo.on('close', this._onClose$, this); } - private _onHide (): void { + private _onHide$ (): void { this.emit(Game.EVENT_HIDE); - this.pauseByEngine(); + this.pauseByEngine$(); } - private _onShow (): void { + private _onShow$ (): void { this.emit(Game.EVENT_SHOW); - this.resumeByEngine(); + this.resumeByEngine$(); } - private _onClose (): void { + private _onClose$ (): void { this.emit(Game.EVENT_CLOSE); // TODO : Release Resources. systemInfo.exit(); @@ -1128,26 +1144,26 @@ export class Game extends EventTarget { return director.isPersistRootNode(node); } - private _setupRenderPipeline (): void | Promise { + private _setupRenderPipeline$ (): void | Promise { const usesCustomPipeline = settings.querySettings( - Settings.Category.RENDERING, + SettingsCategory.RENDERING, 'customPipeline', ); - return this._setRenderPipeline(!!usesCustomPipeline); + return this._setRenderPipeline$(!!usesCustomPipeline); } - private _setRenderPipeline (customPipeline: boolean): void { + private _setRenderPipeline$ (customPipeline: boolean): void { if (!director.root!.setRenderPipeline(customPipeline)) { errorID(1222); return; } - this._rendererInitialized = true; - this._safeEmit(Game.EVENT_RENDERER_INITED); + this._rendererInitialized$ = true; + this._safeEmit$(Game.EVENT_RENDERER_INITED); } - private _safeEmit (event: string | number): void { + private _safeEmit$ (event: string | number): void { if (EDITOR) { try { this.emit(event); diff --git a/cocos/game/splash-screen.ts b/cocos/game/splash-screen.ts index 9f227942ff2..8d75bb9d3d6 100644 --- a/cocos/game/splash-screen.ts +++ b/cocos/game/splash-screen.ts @@ -24,7 +24,7 @@ import { EDITOR, WECHAT } from 'internal:constants'; import { Material } from '../asset/assets/material'; -import { clamp01, Mat4, Vec2, Settings, settings, sys, cclegacy, easing, preTransforms } from '../core'; +import { clamp01, Mat4, Vec2, settings, sys, cclegacy, easing, preTransforms, SettingsCategory } from '../core'; import { Sampler, SamplerInfo, Shader, Texture, TextureInfo, Device, InputAssembler, InputAssemblerInfo, Attribute, Buffer, BufferInfo, Rect, Color, BufferTextureCopy, CommandBuffer, BufferUsageBit, Format, @@ -66,129 +66,122 @@ interface SplashLogo { image?: string; base64?: string; } -const _dsInfo = new DescriptorSetInfo(null!); + export class SplashScreen { - private settings!: ISplashSetting; - private _curTime = 0; - - private device!: Device; - private swapchain!: Swapchain; - private shader!: Shader; - private sampler!: Sampler; - private cmdBuff!: CommandBuffer; - private quadAssmebler!: InputAssembler; - private vertexBuffers!: Buffer; - private indicesBuffers!: Buffer; - private renderArea!: Rect; - private clearColors!: Color[]; - private projection!: Mat4; - private isMobile = false; - - private bgMat!: Material; - private bgImage!: HTMLImageElement; - private bgTexture!: Texture; - - private logoMat!: Material; - private logoImage!: HTMLImageElement; - private logoTexture!: Texture; - - private watermarkMat!: Material; - private watermarkTexture!: Texture; + private settings$!: ISplashSetting; + private _curTime$ = 0; + + private device$!: Device; + private swapchain$!: Swapchain; + private shader$!: Shader; + private sampler$!: Sampler; + private cmdBuff$!: CommandBuffer; + private quadAssmebler$!: InputAssembler; + private vertexBuffers$!: Buffer; + private indicesBuffers$!: Buffer; + private renderArea$!: Rect; + private clearColors$!: Color[]; + private projection$!: Mat4; + private isMobile$ = false; + + private bgMat$!: Material; + private bgImage$!: HTMLImageElement; + private bgTexture$!: Texture; + + private logoMat$!: Material; + private logoImage$!: HTMLImageElement; + private logoTexture$!: Texture; + + private watermarkMat$!: Material; + private watermarkTexture$!: Texture; // layout - private bgWidth = 1920; - private bgHeight = 1080; - private logoWidthTemp = 140; - private logoHeightTemp = 200; - private logoWidth = 0; - private logoHeight = 0; - private logoXTrans = 1 / 2;// Percent - private logoYTrans = 1 / 6 + 2.5 / 6;// Percent - - private textSize = 24; // font size - private textHeight = 24; // line height - private textXTrans = 1 / 2;// Percent - private textYExtraTrans = 32;// px - private textExpandSize = 4;// px - - private scaleSize = 1; + private bgWidth$ = 1920; + private bgHeight$ = 1080; + private logoWidthTemp$ = 140; + private logoHeightTemp$ = 200; + private logoWidth$ = 0; + private logoHeight$ = 0; + private logoXTrans$ = 1 / 2;// Percent + private logoYTrans$ = 1 / 6 + 2.5 / 6;// Percent + + private textSize$ = 24; // font size + private textHeight$ = 24; // line height + private textXTrans$ = 1 / 2;// Percent + private textYExtraTrans$ = 32;// px + private textExpandSize$ = 4;// px + + private scaleSize$ = 1; public get isFinished (): boolean { - if (WECHAT) { - return true; - } - return this._curTime >= this.settings.totalTime; + return this._curTime$ >= this.settings$.totalTime; } set curTime (val) { - this._curTime = val; + this._curTime$ = val; } get curTime (): number { - return this._curTime; + return this._curTime$; } public init (): Promise { - // The WeChat mini-game's splash screen is using the implementation in first-screen. - if (WECHAT) { - return Promise.resolve([]); - } let policy: number = ResolutionPolicy.SHOW_ALL; if (!EDITOR) { - const designResolution = settings.querySettings(Settings.Category.SCREEN, 'designResolution'); + const designResolution = settings.querySettings(SettingsCategory.SCREEN, 'designResolution'); if (designResolution !== null) { policy = designResolution.policy as number; } } - this.settings = { + this.settings$ = { policy: (policy) ?? ResolutionPolicy.SHOW_ALL, - displayRatio: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'displayRatio') ?? 0.4, - totalTime: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'totalTime') ?? 3000, - watermarkLocation: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'watermarkLocation') ?? 'default', - autoFit: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'autoFit') ?? true, - logo: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'logo') ?? undefined, - background: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'background') ?? undefined, + displayRatio: settings.querySettings(SettingsCategory.SPLASH_SCREEN, 'displayRatio') ?? 0.4, + totalTime: settings.querySettings(SettingsCategory.SPLASH_SCREEN, 'totalTime') ?? 3000, + watermarkLocation: settings.querySettings(SettingsCategory.SPLASH_SCREEN, 'watermarkLocation') ?? 'default', + autoFit: settings.querySettings(SettingsCategory.SPLASH_SCREEN, 'autoFit') ?? true, + logo: settings.querySettings(SettingsCategory.SPLASH_SCREEN, 'logo') ?? undefined, + background: settings.querySettings(SettingsCategory.SPLASH_SCREEN, 'background') ?? undefined, }; - this._curTime = 0; + this._curTime$ = 0; - if (EDITOR || this.settings.totalTime <= 0 || this.settings.logo === undefined || this.settings.background === undefined) { - this.settings.totalTime = 0; + if (EDITOR || this.settings$.totalTime <= 0 || this.settings$.logo === undefined || this.settings$.background === undefined) { + this.settings$.totalTime = 0; } else { - this.device = cclegacy.director.root!.device; - this.swapchain = cclegacy.director.root!.mainWindow!.swapchain; + this.device$ = cclegacy.director.root!.device; + this.swapchain$ = cclegacy.director.root!.mainWindow!.swapchain; - this.preInit(); - this.initLayout(); + this.preInit$(); + this.initLayout$(); - if (this.settings.logo.type === 'default') { - this.initWaterMark(); + if (this.settings$.logo.type === 'default') { + this.initWaterMark$(); } let bgPromise = Promise.resolve(); let logoPromise = Promise.resolve(); - if (this.settings.background.type === 'custom') { + if (this.settings$.background.type === 'custom') { bgPromise = new Promise((resolve, reject): void => { - this.bgImage = new ccwindow.Image(); - this.bgImage.onload = (): void => { - this.initBG(); + this.bgImage$ = new ccwindow.Image(); + this.bgImage$.onload = (): void => { + this.initBG$(); resolve(); }; - this.bgImage.onerror = (): void => { + this.bgImage$.onerror = (): void => { reject(); }; - this.bgImage.src = this.settings.background!.base64!; + this.bgImage$.src = this.settings$.background!.base64!; }); } - if (this.settings.logo.type !== 'none') { + if (this.settings$.logo.type !== 'none') { logoPromise = new Promise((resolve, reject): void => { - this.logoImage = new ccwindow.Image(); - this.logoImage.onload = (): void => { - this.initLogo(); + this.logoImage$ = new ccwindow.Image(); + this.logoImage$.onload = (): void => { + this.initLogo$(); resolve(); }; - this.logoImage.onerror = (): void => { + this.logoImage$.onerror = (): void => { reject(); }; - this.logoImage.src = this.settings.logo!.base64!; + this.logoImage$.src = this.settings$.logo!.base64!; }); } return Promise.all([bgPromise, logoPromise]); @@ -196,51 +189,48 @@ export class SplashScreen { return Promise.resolve([]); } - private preInit (): void { - if (WECHAT) { - return; - } - const clearColor = this.settings.background?.color; - this.clearColors = clearColor ? [new Color(clearColor.x, clearColor.y, clearColor.z, clearColor.w)] : [new Color(0, 0, 0, 1)]; - const { device, swapchain } = this; - this.renderArea = new Rect(0, 0, swapchain.width, swapchain.height); - this.cmdBuff = device.commandBuffer; + private preInit$ (): void { + const clearColor = this.settings$.background?.color; + this.clearColors$ = clearColor ? [new Color(clearColor.x, clearColor.y, clearColor.z, clearColor.w)] : [new Color(0, 0, 0, 1)]; + const { device$: device, swapchain$: swapchain } = this; + this.renderArea$ = new Rect(0, 0, swapchain.width, swapchain.height); + this.cmdBuff$ = device.commandBuffer; // create input assembler // create vertex buffer const verts = new Float32Array([0.5, 0.5, 1, 0, -0.5, 0.5, 0, 0, 0.5, -0.5, 1, 1, -0.5, -0.5, 0, 1]); const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; const vbSize = vbStride * 4; - this.vertexBuffers = device.createBuffer(new BufferInfo( + this.vertexBuffers$ = device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbSize, vbStride, )); - this.vertexBuffers.update(verts); + this.vertexBuffers$.update(verts); // create index buffer const indices = new Uint16Array([0, 1, 2, 1, 3, 2]); const ibStride = Uint16Array.BYTES_PER_ELEMENT; const ibSize = ibStride * 6; - this.indicesBuffers = device.createBuffer(new BufferInfo( + this.indicesBuffers$ = device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride, )); - this.indicesBuffers.update(indices); + this.indicesBuffers$.update(indices); const attributes: Attribute[] = [ new Attribute('a_position', Format.RG32F), new Attribute('a_texCoord', Format.RG32F), ]; - const IAInfo = new InputAssemblerInfo(attributes, [this.vertexBuffers], this.indicesBuffers); - this.quadAssmebler = device.createInputAssembler(IAInfo); + const IAInfo = new InputAssemblerInfo(attributes, [this.vertexBuffers$], this.indicesBuffers$); + this.quadAssmebler$ = device.createInputAssembler(IAInfo); - this.projection = new Mat4(); + this.projection$ = new Mat4(); Mat4.ortho( - this.projection, + this.projection$, -1, 1, -1, @@ -252,68 +242,59 @@ export class SplashScreen { swapchain.surfaceTransform, ); - this.isMobile = sys.isMobile; + this.isMobile$ = sys.isMobile; } - private initLayout (): void { - if (WECHAT) { - return; - } - if (this.isMobile) { - this.bgWidth = 812; - this.bgHeight = 375; + private initLayout$ (): void { + if (this.isMobile$) { + this.bgWidth$ = 812; + this.bgHeight$ = 375; - this.logoWidthTemp = 70; - this.logoHeightTemp = 100; + this.logoWidthTemp$ = 70; + this.logoHeightTemp$ = 100; - this.textSize = 12; // font size - this.textHeight = this.textSize + this.textExpandSize; // line height - this.textXTrans = 1 / 2;// Percent - this.textYExtraTrans = 16;// px + this.textSize$ = 12; // font size + this.textHeight$ = this.textSize$ + this.textExpandSize$; // line height + this.textXTrans$ = 1 / 2;// Percent + this.textYExtraTrans$ = 16;// px } else { - this.bgWidth = 1920; - this.bgHeight = 1080; + this.bgWidth$ = 1920; + this.bgHeight$ = 1080; - this.logoWidthTemp = 140; - this.logoHeightTemp = 200; + this.logoWidthTemp$ = 140; + this.logoHeightTemp$ = 200; - this.textSize = 24; // font size - this.textHeight = this.textSize + this.textExpandSize; // line height - this.textXTrans = 1 / 2;// Percent - this.textYExtraTrans = 32;// px + this.textSize$ = 24; // font size + this.textHeight$ = this.textSize$ + this.textExpandSize$; // line height + this.textXTrans$ = 1 / 2;// Percent + this.textYExtraTrans$ = 32;// px } - this.logoXTrans = 1 / 2;// Percent - this.logoYTrans = 1 / 6 + 2.5 / 6;// Percent - this.initScale(); + this.logoXTrans$ = 1 / 2;// Percent + this.logoYTrans$ = 1 / 6 + 2.5 / 6;// Percent + this.initScale$(); } - private initScale (): void { - if (WECHAT) { - return; - } - const dw = this.swapchain.width; const dh = this.swapchain.height; - let desiredWidth = this.isMobile ? 375 : 1080; - let desiredHeight = this.isMobile ? 812 : 1920; + private initScale$ (): void { + const dw = this.swapchain$.width; const dh = this.swapchain$.height; + let desiredWidth = this.isMobile$ ? 375 : 1080; + let desiredHeight = this.isMobile$ ? 812 : 1920; if (dw > dh) { const temp = desiredHeight; desiredHeight = desiredWidth; desiredWidth = temp; } if (dw / dh > 16 / 9) { - this.scaleSize = dh / desiredHeight; + this.scaleSize$ = dh / desiredHeight; } else { - this.scaleSize = dw / desiredWidth; + this.scaleSize$ = dw / desiredWidth; } } public update (deltaTime: number): void { - if (WECHAT) { - return; - } - const settings = this.settings; - const { device, swapchain } = this; + const settings = this.settings$; + const { device$: device, swapchain$: swapchain } = this; Mat4.ortho( - this.projection, + this.projection$, -1, 1, -1, @@ -325,207 +306,195 @@ export class SplashScreen { swapchain.surfaceTransform, ); const dw = swapchain.width; const dh = swapchain.height; - this.initScale(); + this.initScale$(); - this._curTime += deltaTime * 1000; - const percent = clamp01(this._curTime / settings.totalTime); + this._curTime$ += deltaTime * 1000; + const percent = clamp01(this._curTime$ / settings.totalTime); const u_p = easing.cubicOut(percent); let scaleX = 1; let scaleY = 1; // update bg uniform - if (this.settings.background!.type === 'custom') { - if (this.settings.policy === ResolutionPolicy.FIXED_WIDTH) { + if (this.settings$.background!.type === 'custom') { + if (this.settings$.policy === ResolutionPolicy.FIXED_WIDTH) { scaleX = dw; - scaleY = (dw / this.bgImage.width) * this.bgImage.height; - } else if (this.settings.policy === ResolutionPolicy.FIXED_HEIGHT) { - scaleX = (dh / this.bgImage.height) * this.bgImage.width; + scaleY = (dw / this.bgImage$.width) * this.bgImage$.height; + } else if (this.settings$.policy === ResolutionPolicy.FIXED_HEIGHT) { + scaleX = (dh / this.bgImage$.height) * this.bgImage$.width; scaleY = dh; - } else if (this.settings.policy === ResolutionPolicy.SHOW_ALL) { - if ((this.bgImage.width / this.bgHeight) > (dw / dh)) { + } else if (this.settings$.policy === ResolutionPolicy.SHOW_ALL) { + if ((this.bgImage$.width / this.bgHeight$) > (dw / dh)) { scaleX = dw; - scaleY = (dw / this.bgImage.width) * this.bgImage.height; + scaleY = (dw / this.bgImage$.width) * this.bgImage$.height; } else { - scaleX = (dh / this.bgImage.height) * this.bgImage.width; + scaleX = (dh / this.bgImage$.height) * this.bgImage$.width; scaleY = dh; } - } else if (this.settings.policy === ResolutionPolicy.NO_BORDER) { - if ((this.bgImage.width / this.bgImage.height) > (dw / dh)) { - scaleX = (dh / this.bgImage.height) * this.bgImage.width; + } else if (this.settings$.policy === ResolutionPolicy.NO_BORDER) { + if ((this.bgImage$.width / this.bgImage$.height) > (dw / dh)) { + scaleX = (dh / this.bgImage$.height) * this.bgImage$.width; scaleY = dh; } else { scaleX = dw; - scaleY = (dw / this.bgImage.width) * this.bgImage.height; + scaleY = (dw / this.bgImage$.width) * this.bgImage$.height; } } else { scaleX = dw; scaleY = dh; } - this.bgMat.setProperty('resolution', v2_0.set(dw, dh), 0); - this.bgMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); - this.bgMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0); - this.bgMat.setProperty('percent', 1.0); - this.bgMat.setProperty('u_projection', this.projection); - this.bgMat.passes[0].update(); + this.bgMat$.setProperty('resolution', v2_0.set(dw, dh), 0); + this.bgMat$.setProperty('scale', v2_0.set(scaleX, scaleY), 0); + this.bgMat$.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0); + this.bgMat$.setProperty('percent', 1.0); + this.bgMat$.setProperty('u_projection', this.projection$); + this.bgMat$.passes[0].update(); } // update logo uniform - const logoYTrans = dh * this.logoYTrans; - if (this.settings.logo!.type !== 'none') { + const logoYTrans = dh * this.logoYTrans$; + if (this.settings$.logo!.type !== 'none') { // Product design is 0.185 of the height of the screen resolution as the display height of the logo. scaleY = dh * 0.185 * settings.displayRatio; - scaleX = this.logoWidth * (dh * 0.185 / this.logoHeight) * settings.displayRatio; - this.logoMat.setProperty('resolution', v2_0.set(dw, dh), 0); - this.logoMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); - this.logoMat.setProperty('translate', v2_0.set(dw * this.logoXTrans, logoYTrans), 0); - this.logoMat.setProperty('percent', u_p); - this.logoMat.setProperty('u_projection', this.projection); - this.logoMat.passes[0].update(); + scaleX = this.logoWidth$ * (dh * 0.185 / this.logoHeight$) * settings.displayRatio; + this.logoMat$.setProperty('resolution', v2_0.set(dw, dh), 0); + this.logoMat$.setProperty('scale', v2_0.set(scaleX, scaleY), 0); + this.logoMat$.setProperty('translate', v2_0.set(dw * this.logoXTrans$, logoYTrans), 0); + this.logoMat$.setProperty('percent', u_p); + this.logoMat$.setProperty('u_projection', this.projection$); + this.logoMat$.passes[0].update(); } // update watermark uniform - if (this.settings.logo!.type === 'default' && this.watermarkMat) { - const watermarkTW = this.watermarkTexture.width; const watermarkTH = this.watermarkTexture.height; + if (this.settings$.logo!.type === 'default' && this.watermarkMat$) { + const watermarkTW = this.watermarkTexture$.width; const watermarkTH = this.watermarkTexture$.height; scaleX = watermarkTW; scaleY = watermarkTH; - const textYTrans = logoYTrans - (this.logoHeight * 0.5 * settings.displayRatio + this.textYExtraTrans) - * this.scaleSize - watermarkTH * 0.5; - this.watermarkMat.setProperty('resolution', v2_0.set(dw, dh), 0); - this.watermarkMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); - this.watermarkMat.setProperty('translate', v2_0.set(dw * this.textXTrans, textYTrans), 0); - this.watermarkMat.setProperty('percent', u_p); - this.watermarkMat.setProperty('u_projection', this.projection); - this.watermarkMat.passes[0].update(); + const textYTrans = logoYTrans - (this.logoHeight$ * 0.5 * settings.displayRatio + this.textYExtraTrans$) + * this.scaleSize$ - watermarkTH * 0.5; + this.watermarkMat$.setProperty('resolution', v2_0.set(dw, dh), 0); + this.watermarkMat$.setProperty('scale', v2_0.set(scaleX, scaleY), 0); + this.watermarkMat$.setProperty('translate', v2_0.set(dw * this.textXTrans$, textYTrans), 0); + this.watermarkMat$.setProperty('percent', u_p); + this.watermarkMat$.setProperty('u_projection', this.projection$); + this.watermarkMat$.passes[0].update(); } - this.frame(); + this.frame$(); } - private initBG (): void { - if (WECHAT) { - return; - } - const device = this.device; + private initBG$ (): void { + const device = this.device$; - this.bgMat = new Material(); - this.bgMat.initialize({ effectName: 'util/splash-screen' }); + this.bgMat$ = new Material(); + this.bgMat$.initialize({ effectName: 'util/splash-screen' }); const samplerInfo = new SamplerInfo(); samplerInfo.addressU = Address.CLAMP; samplerInfo.addressV = Address.CLAMP; samplerInfo.addressW = Address.CLAMP; - this.sampler = device.getSampler(samplerInfo); + this.sampler$ = device.getSampler(samplerInfo); - this.bgTexture = device.createTexture(new TextureInfo( + this.bgTexture$ = device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, - this.bgImage.width, - this.bgImage.height, + this.bgImage$.width, + this.bgImage$.height, )); - const pass = this.bgMat.passes[0]; + const pass = this.bgMat$.passes[0]; const binding = pass.getBinding('mainTexture'); - pass.bindTexture(binding, this.bgTexture); - this.shader = pass.getShaderVariant()!; + pass.bindTexture(binding, this.bgTexture$); + this.shader$ = pass.getShaderVariant()!; const descriptorSet = pass.descriptorSet; - descriptorSet.bindSampler(binding, this.sampler); + descriptorSet.bindSampler(binding, this.sampler$); descriptorSet.update(); const region = new BufferTextureCopy(); - region.texExtent.width = this.bgImage.width; - region.texExtent.height = this.bgImage.height; + region.texExtent.width = this.bgImage$.width; + region.texExtent.height = this.bgImage$.height; region.texExtent.depth = 1; - device.copyTexImagesToTexture([this.bgImage], this.bgTexture, [region]); + device.copyTexImagesToTexture([this.bgImage$], this.bgTexture$, [region]); } - private initLogo (): void { - if (WECHAT) { - return; - } - const device = this.device; + private initLogo$ (): void { + const device = this.device$; - this.logoMat = new Material(); - this.logoMat.initialize({ effectName: 'util/splash-screen' }); + this.logoMat$ = new Material(); + this.logoMat$.initialize({ effectName: 'util/splash-screen' }); const samplerInfo = new SamplerInfo(); samplerInfo.addressU = Address.CLAMP; samplerInfo.addressV = Address.CLAMP; samplerInfo.addressW = Address.CLAMP; - this.sampler = device.getSampler(samplerInfo); + this.sampler$ = device.getSampler(samplerInfo); - this.logoTexture = device.createTexture(new TextureInfo( + this.logoTexture$ = device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, - this.logoImage.width, - this.logoImage.height, + this.logoImage$.width, + this.logoImage$.height, )); - const pass = this.logoMat.passes[0]; + const pass = this.logoMat$.passes[0]; const binding = pass.getBinding('mainTexture'); - pass.bindTexture(binding, this.logoTexture); - this.shader = pass.getShaderVariant()!; + pass.bindTexture(binding, this.logoTexture$); + this.shader$ = pass.getShaderVariant()!; const descriptorSet = pass.descriptorSet; - descriptorSet.bindSampler(binding, this.sampler); + descriptorSet.bindSampler(binding, this.sampler$); descriptorSet.update(); const region = new BufferTextureCopy(); - region.texExtent.width = this.logoImage.width; - region.texExtent.height = this.logoImage.height; + region.texExtent.width = this.logoImage$.width; + region.texExtent.height = this.logoImage$.height; region.texExtent.depth = 1; - device.copyTexImagesToTexture([this.logoImage], this.logoTexture, [region]); + device.copyTexImagesToTexture([this.logoImage$], this.logoTexture$, [region]); - const logoRatio = this.logoImage.width / this.logoImage.height; + const logoRatio = this.logoImage$.width / this.logoImage$.height; if (logoRatio < 1) { - this.logoWidth = this.logoWidthTemp; - this.logoHeight = this.logoWidthTemp / logoRatio; + this.logoWidth$ = this.logoWidthTemp$; + this.logoHeight$ = this.logoWidthTemp$ / logoRatio; } else { - this.logoWidth = this.logoHeightTemp * logoRatio; - this.logoHeight = this.logoHeightTemp; + this.logoWidth$ = this.logoHeightTemp$ * logoRatio; + this.logoHeight$ = this.logoHeightTemp$; } } - private initWaterMark (): void { - if (WECHAT) { - return; - } + private initWaterMark$ (): void { // create texture from image const watermarkImg = ccwindow.document.createElement('canvas'); - watermarkImg.height = this.textHeight * this.scaleSize; + watermarkImg.height = this.textHeight$ * this.scaleSize$; watermarkImg.style.width = `${watermarkImg.width}`; watermarkImg.style.height = `${watermarkImg.height}`; const text = 'Created with Cocos'; const ctx = watermarkImg.getContext('2d')!; - ctx.font = `${this.textSize * this.scaleSize}px Arial`; ctx.textBaseline = 'top'; ctx.textAlign = 'center'; ctx.fillStyle = '#707070'; + ctx.font = `${this.textSize$ * this.scaleSize$}px Arial`; ctx.textBaseline = 'top'; ctx.textAlign = 'center'; ctx.fillStyle = '#707070'; const textLength = ctx.measureText(text).width + 10; watermarkImg.width = textLength; // Tips: Set canvas width will clean context style - ctx.font = `${this.textSize * this.scaleSize}px Arial`; ctx.textBaseline = 'top'; ctx.textAlign = 'center'; ctx.fillStyle = '#707070'; + ctx.font = `${this.textSize$ * this.scaleSize$}px Arial`; ctx.textBaseline = 'top'; ctx.textAlign = 'center'; ctx.fillStyle = '#707070'; ctx.fillText(text, watermarkImg.width / 2, 0); const region = new BufferTextureCopy(); region.texExtent.width = watermarkImg.width; region.texExtent.height = watermarkImg.height; region.texExtent.depth = 1; - this.watermarkTexture = this.device.createTexture(new TextureInfo( + this.watermarkTexture$ = this.device$.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, watermarkImg.width, watermarkImg.height, )); - this.device.copyTexImagesToTexture([watermarkImg], this.watermarkTexture, [region]); + this.device$.copyTexImagesToTexture([watermarkImg], this.watermarkTexture$, [region]); // create material - this.watermarkMat = new Material(); - this.watermarkMat.initialize({ effectName: 'util/splash-screen' }); - const pass = this.watermarkMat.passes[0]; + this.watermarkMat$ = new Material(); + this.watermarkMat$.initialize({ effectName: 'util/splash-screen' }); + const pass = this.watermarkMat$.passes[0]; const binding = pass.getBinding('mainTexture'); - pass.bindTexture(binding, this.watermarkTexture); + pass.bindTexture(binding, this.watermarkTexture$); pass.descriptorSet.update(); } - private frame (): void { - if (WECHAT) { - return; - } - const { device, swapchain } = this; + private frame$ (): void { + const { device$: device, swapchain$: swapchain } = this; if (!sys.isXR || xr.entry.isRenderAllowable()) { const renderSize = sys.isXR ? 2 : 1; @@ -542,7 +511,7 @@ export class SplashScreen { radioRight = Math.abs(Math.tan(xrFov[1] as number)) / Math.abs(Math.tan(xrFov[0] as number)); } Mat4.ortho( - this.projection, + this.projection$, -radioLeft, radioRight, -1, @@ -554,19 +523,19 @@ export class SplashScreen { swapchain.surfaceTransform, ); // keep scale to [-1, 1] only use offset - this.projection.m00 = preTransforms[swapchain.surfaceTransform][0]; - this.projection.m05 = preTransforms[swapchain.surfaceTransform][3] * device.capabilities.clipSpaceSignY; - if (this.settings.background!.type === 'custom') { - this.bgMat.setProperty('u_projection', this.projection); - this.bgMat.passes[0].update(); + this.projection$.m00 = preTransforms[swapchain.surfaceTransform][0]; + this.projection$.m05 = preTransforms[swapchain.surfaceTransform][3] * device.capabilities.clipSpaceSignY; + if (this.settings$.background!.type === 'custom') { + this.bgMat$.setProperty('u_projection', this.projection$); + this.bgMat$.passes[0].update(); } - if (this.settings.logo!.type !== 'none') { - this.logoMat.setProperty('u_projection', this.projection); - this.logoMat.passes[0].update(); + if (this.settings$.logo!.type !== 'none') { + this.logoMat$.setProperty('u_projection', this.projection$); + this.logoMat$.passes[0].update(); } - if (this.settings.logo!.type === 'default' && this.watermarkMat) { - this.watermarkMat.setProperty('u_projection', this.projection); - this.watermarkMat.passes[0].update(); + if (this.settings$.logo!.type === 'default' && this.watermarkMat$) { + this.watermarkMat$.setProperty('u_projection', this.projection$); + this.watermarkMat$.passes[0].update(); } } @@ -575,65 +544,65 @@ export class SplashScreen { device.acquire([swapchain]); // record command - const cmdBuff = this.cmdBuff; + const cmdBuff = this.cmdBuff$; const framebuffer = cclegacy.director.root!.mainWindow!.framebuffer as Framebuffer; - const renderArea = this.renderArea; + const renderArea = this.renderArea$; renderArea.width = swapchain.width; renderArea.height = swapchain.height; cmdBuff.begin(); - cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0); + cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors$, 1.0, 0); const pipeline = cclegacy.director.root.pipeline as PipelineRuntime; - if (this.settings.background!.type === 'custom') { - const bgPass = this.bgMat.passes[0]; + if (this.settings$.background!.type === 'custom') { + const bgPass = this.bgMat$.passes[0]; const bgPso = PipelineStateManager.getOrCreatePipelineState( device, bgPass, - this.shader, + this.shader$, framebuffer.renderPass, - this.quadAssmebler, + this.quadAssmebler$, ); cmdBuff.bindPipelineState(bgPso); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, bgPass.descriptorSet); - cmdBuff.bindInputAssembler(this.quadAssmebler); - cmdBuff.draw(this.quadAssmebler); + cmdBuff.bindInputAssembler(this.quadAssmebler$); + cmdBuff.draw(this.quadAssmebler$); } - if (this.settings.logo!.type !== 'none') { - const logoPass = this.logoMat.passes[0]; + if (this.settings$.logo!.type !== 'none') { + const logoPass = this.logoMat$.passes[0]; const logoPso = PipelineStateManager.getOrCreatePipelineState( device, logoPass, - this.shader, + this.shader$, framebuffer.renderPass, - this.quadAssmebler, + this.quadAssmebler$, ); cmdBuff.bindPipelineState(logoPso); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet); - cmdBuff.bindInputAssembler(this.quadAssmebler); - cmdBuff.draw(this.quadAssmebler); + cmdBuff.bindInputAssembler(this.quadAssmebler$); + cmdBuff.draw(this.quadAssmebler$); } - if (this.settings.logo!.type === 'default' && this.watermarkMat) { - const wartermarkPass = this.watermarkMat.passes[0]; + if (this.settings$.logo!.type === 'default' && this.watermarkMat$) { + const wartermarkPass = this.watermarkMat$.passes[0]; const watermarkPso = PipelineStateManager.getOrCreatePipelineState( device, wartermarkPass, - this.shader, + this.shader$, framebuffer.renderPass, - this.quadAssmebler, + this.quadAssmebler$, ); cmdBuff.bindPipelineState(watermarkPso); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet); - cmdBuff.bindInputAssembler(this.quadAssmebler); - cmdBuff.draw(this.quadAssmebler); + cmdBuff.bindInputAssembler(this.quadAssmebler$); + cmdBuff.draw(this.quadAssmebler$); } cmdBuff.endRenderPass(); @@ -650,59 +619,93 @@ export class SplashScreen { } } - private destroy (): void { - if (WECHAT) { - return; + private destroy$ (): void { + this.device$ = null!; + this.swapchain$ = null!; + this.clearColors$ = null!; + + if (this.bgImage$) { + if ((this.bgImage$ as any).destroy) (this.bgImage$ as any).destroy(); + this.bgImage$ = null!; } - this.device = null!; - this.swapchain = null!; - this.clearColors = null!; - if (this.settings.background!.type === 'custom') { - if ((this.bgImage as any).destroy) (this.bgImage as any).destroy(); - this.bgImage = null!; - this.bgMat.destroy(); - this.bgMat = null!; - this.bgTexture.destroy(); - this.bgTexture = null!; + + if (this.bgMat$) { + this.bgMat$.destroy(); + this.bgMat$ = null!; } - if (this.settings.logo!.type !== 'none') { - if ((this.logoImage as any).destroy) (this.logoImage as any).destroy(); - this.logoImage = null!; - this.logoMat.destroy(); - this.logoMat = null!; - this.logoTexture.destroy(); - this.logoTexture = null!; + + if (this.bgTexture$) { + this.bgTexture$.destroy(); + this.bgTexture$ = null!; } - this.renderArea = null!; - this.cmdBuff = null!; - this.shader = null!; - this.quadAssmebler.destroy(); - this.quadAssmebler = null!; - this.vertexBuffers.destroy(); - this.vertexBuffers = null!; - this.indicesBuffers.destroy(); - this.indicesBuffers = null!; - this.sampler = null!; + + if (this.logoImage$) { + if ((this.logoImage$ as any).destroy) (this.logoImage$ as any).destroy(); + this.logoImage$ = null!; + } + + if (this.logoMat$) { + this.logoMat$.destroy(); + this.logoMat$ = null!; + } + + if (this.logoTexture$) { + this.logoTexture$.destroy(); + this.logoTexture$ = null!; + } + + this.renderArea$ = null!; + this.cmdBuff$ = null!; + this.shader$ = null!; + + if (this.quadAssmebler$) { + this.quadAssmebler$.destroy(); + this.quadAssmebler$ = null!; + } + + if (this.vertexBuffers$) { + this.vertexBuffers$.destroy(); + this.vertexBuffers$ = null!; + } + + if (this.indicesBuffers$) { + this.indicesBuffers$.destroy(); + this.indicesBuffers$ = null!; + } + this.sampler$ = null!; /** text */ - if (this.settings.logo!.type === 'default' && this.watermarkTexture) { - this.watermarkMat.destroy(); - this.watermarkMat = null!; - this.watermarkTexture.destroy(); - this.watermarkTexture = null!; + if (this.watermarkMat$) { + this.watermarkMat$.destroy(); + this.watermarkMat$ = null!; + } + + if (this.watermarkTexture$) { + this.watermarkTexture$.destroy(); + this.watermarkTexture$ = null!; } - this.settings = null!; + this.settings$ = null!; } - private static _ins?: SplashScreen; + private static _ins: SplashScreen | null = null; - public static get instance (): SplashScreen { - if (!SplashScreen._ins) { - SplashScreen._ins = new SplashScreen(); - } + public static get instance (): SplashScreen | null { + return SplashScreen._ins; + } + + public static createInstance (): SplashScreen { + SplashScreen._ins = new SplashScreen(); return SplashScreen._ins; } + + public static releaseInstance (): void { + if (SplashScreen._ins) { + SplashScreen._ins.destroy$(); + SplashScreen._ins = null; + } + } + // eslint-disable-next-line no-empty-function private constructor () {} } diff --git a/cocos/input/input.ts b/cocos/input/input.ts index 618193bc1f3..89d8dcdc4be 100644 --- a/cocos/input/input.ts +++ b/cocos/input/input.ts @@ -52,10 +52,10 @@ export interface IEventDispatcher { class InputEventDispatcher implements IEventDispatcher { public priority: EventDispatcherPriority = EventDispatcherPriority.GLOBAL; - private declare _inputEventTarget: EventTarget; + private declare _inputEventTarget$: EventTarget; constructor (inputEventTarget: EventTarget) { - this._inputEventTarget = inputEventTarget; + this._inputEventTarget$ = inputEventTarget; } onThrowException (): void { @@ -63,7 +63,7 @@ class InputEventDispatcher implements IEventDispatcher { } public dispatchEvent (event: Event): boolean { - this._inputEventTarget.emit(event.type, event); + this._inputEventTarget$.emit(event.type, event); return true; } } @@ -79,24 +79,24 @@ export declare namespace Input { } interface InputEventMap { - [Input.EventType.MOUSE_DOWN]: (event: EventMouse) => void, - [Input.EventType.MOUSE_MOVE]: (event: EventMouse) => void, - [Input.EventType.MOUSE_UP]: (event: EventMouse) => void, - [Input.EventType.MOUSE_WHEEL]: (event: EventMouse) => void, - [Input.EventType.TOUCH_START]: (event: EventTouch) => void, - [Input.EventType.TOUCH_MOVE]: (event: EventTouch) => void, - [Input.EventType.TOUCH_END]: (event: EventTouch) => void, - [Input.EventType.TOUCH_CANCEL]: (event: EventTouch) => void, - [Input.EventType.KEY_DOWN]: (event: EventKeyboard) => void, - [Input.EventType.KEY_PRESSING]: (event: EventKeyboard) => void, - [Input.EventType.KEY_UP]: (event: EventKeyboard) => void, - [Input.EventType.DEVICEMOTION]: (event: EventAcceleration) => void, - [Input.EventType.GAMEPAD_CHANGE]: (event: EventGamepad) => void, - [Input.EventType.GAMEPAD_INPUT]: (event: EventGamepad) => void, - [Input.EventType.HANDLE_INPUT]: (event: EventHandle) => void, - [Input.EventType.HANDLE_POSE_INPUT]: (event: EventHandle) => void, - [Input.EventType.HMD_POSE_INPUT]: (event: EventHMD) => void, - [Input.EventType.HANDHELD_POSE_INPUT]: (event: EventHandheld) => void, + [InputEventType.MOUSE_DOWN]: (event: EventMouse) => void, + [InputEventType.MOUSE_MOVE]: (event: EventMouse) => void, + [InputEventType.MOUSE_UP]: (event: EventMouse) => void, + [InputEventType.MOUSE_WHEEL]: (event: EventMouse) => void, + [InputEventType.TOUCH_START]: (event: EventTouch) => void, + [InputEventType.TOUCH_MOVE]: (event: EventTouch) => void, + [InputEventType.TOUCH_END]: (event: EventTouch) => void, + [InputEventType.TOUCH_CANCEL]: (event: EventTouch) => void, + [InputEventType.KEY_DOWN]: (event: EventKeyboard) => void, + [InputEventType.KEY_PRESSING]: (event: EventKeyboard) => void, + [InputEventType.KEY_UP]: (event: EventKeyboard) => void, + [InputEventType.DEVICEMOTION]: (event: EventAcceleration) => void, + [InputEventType.GAMEPAD_CHANGE]: (event: EventGamepad) => void, + [InputEventType.GAMEPAD_INPUT]: (event: EventGamepad) => void, + [InputEventType.HANDLE_INPUT]: (event: EventHandle) => void, + [InputEventType.HANDLE_POSE_INPUT]: (event: EventHandle) => void, + [InputEventType.HMD_POSE_INPUT]: (event: EventHMD) => void, + [InputEventType.HANDHELD_POSE_INPUT]: (event: EventHandheld) => void, } /** @@ -110,8 +110,8 @@ interface InputEventMap { * * @example * ``` - * input.on(Input.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); - * input.off(Input.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * input.on(InputEventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * input.off(InputEventType.DEVICEMOTION, this.onDeviceMotionEvent, this); * ``` */ export class Input { @@ -131,35 +131,35 @@ export class Input { * 输入事件默认会被收集到每一帧主循环里派发,如果你需要立即接收到输入事件,请把该属性设为 true。 * 注意:如果设置为 true,则输入事件可能会在帧间触发,这样的输入事件是没办法被引擎优化的。 */ - private _dispatchImmediately = !NATIVE; - - private _eventTarget: EventTarget = new EventTarget(); - private _touchInput = new TouchInputSource(); - private _mouseInput = new MouseInputSource(); - private _keyboardInput = new KeyboardInputSource(); - private _accelerometerInput = new AccelerometerInputSource(); - private _handleInput = new HandleInputDevice(); - private _hmdInput = new HMDInputDevice(); - private _handheldInput = new HandheldInputDevice(); - - private _eventTouchList: EventTouch[] = []; - private _eventMouseList: EventMouse[] = []; - private _eventKeyboardList: EventKeyboard[] = []; - private _eventAccelerationList: EventAcceleration[] = []; - private _eventGamepadList: EventGamepad[] = []; - private _eventHandleList: EventHandle[] = []; - private _eventHMDList: EventHMD[] = []; - private _eventHandheldList: EventHandheld[] = []; - - private _needSimulateTouchMoveEvent = false; - - private declare _inputEventDispatcher: InputEventDispatcher; - private _eventDispatcherList: IEventDispatcher[] = []; + private _dispatchImmediately$ = !NATIVE; + + private _eventTarget$: EventTarget = new EventTarget(); + private _touchInput$ = new TouchInputSource(); + private _mouseInput$ = new MouseInputSource(); + private _keyboardInput$ = new KeyboardInputSource(); + private _accelerometerInput$ = new AccelerometerInputSource(); + private _handleInput$ = new HandleInputDevice(); + private _hmdInput$ = new HMDInputDevice(); + private _handheldInput$ = new HandheldInputDevice(); + + private _eventTouchList$: EventTouch[] = []; + private _eventMouseList$: EventMouse[] = []; + private _eventKeyboardList$: EventKeyboard[] = []; + private _eventAccelerationList$: EventAcceleration[] = []; + private _eventGamepadList$: EventGamepad[] = []; + private _eventHandleList$: EventHandle[] = []; + private _eventHMDList$: EventHMD[] = []; + private _eventHandheldList$: EventHandheld[] = []; + + private _needSimulateTouchMoveEvent$ = false; + + private declare _inputEventDispatcher$: InputEventDispatcher; + private _eventDispatcherList$: IEventDispatcher[] = []; constructor () { - this._registerEvent(); - this._inputEventDispatcher = new InputEventDispatcher(this._eventTarget); - this._registerEventDispatcher(this._inputEventDispatcher); + this._registerEvent$(); + this._inputEventDispatcher$ = new InputEventDispatcher(this._eventTarget$); + this._registerEventDispatcher(this._inputEventDispatcher$); GamepadInputDevice._init(); } @@ -167,38 +167,38 @@ export class Input { * This should be a private method, but it's exposed for Editor Only. */ private _dispatchMouseDownEvent (nativeMouseEvent: any): void { - this._mouseInput.dispatchMouseDownEvent?.(nativeMouseEvent); + this._mouseInput$.dispatchMouseDownEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ private _dispatchMouseMoveEvent (nativeMouseEvent: any): void { - this._mouseInput.dispatchMouseMoveEvent?.(nativeMouseEvent); + this._mouseInput$.dispatchMouseMoveEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ private _dispatchMouseUpEvent (nativeMouseEvent: any): void { - this._mouseInput.dispatchMouseUpEvent?.(nativeMouseEvent); + this._mouseInput$.dispatchMouseUpEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ private _dispatchMouseScrollEvent (nativeMouseEvent: any): void { - this._mouseInput.dispatchScrollEvent?.(nativeMouseEvent); + this._mouseInput$.dispatchScrollEvent?.(nativeMouseEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ private _dispatchKeyboardDownEvent (nativeKeyboardEvent: any): void { - this._keyboardInput.dispatchKeyboardDownEvent?.(nativeKeyboardEvent); + this._keyboardInput$.dispatchKeyboardDownEvent?.(nativeKeyboardEvent); } /** * This should be a private method, but it's exposed for Editor Only. */ private _dispatchKeyboardUpEvent (nativeKeyboardEvent: any): void { - this._keyboardInput.dispatchKeyboardUpEvent?.(nativeKeyboardEvent); + this._keyboardInput$.dispatchKeyboardUpEvent?.(nativeKeyboardEvent); } /** @@ -212,7 +212,7 @@ export class Input { * @param target - The event listener's target and callee */ public on (eventType: K, callback: InputEventMap[K], target?: any): InputEventMap[K] { - this._eventTarget.on(eventType, callback, target); + this._eventTarget$.on(eventType, callback, target); return callback; } @@ -227,7 +227,7 @@ export class Input { * @param target - The event listener's target and callee */ public once (eventType: K, callback: InputEventMap[K], target?: any): InputEventMap[K] { - this._eventTarget.once(eventType, callback, target); + this._eventTarget$.once(eventType, callback, target); return callback; } @@ -245,7 +245,7 @@ export class Input { if (EDITOR_NOT_IN_PREVIEW) { return; } - this._eventTarget.off(eventType, callback, target); + this._eventTarget$.off(eventType, callback, target); } /** @@ -290,9 +290,9 @@ export class Input { return; } if (isEnable) { - this._accelerometerInput.start(); + this._accelerometerInput$.start(); } else { - this._accelerometerInput.stop(); + this._accelerometerInput$.stop(); } } @@ -307,10 +307,10 @@ export class Input { if (EDITOR_NOT_IN_PREVIEW) { return; } - this._accelerometerInput.setInterval(intervalInMileSeconds); + this._accelerometerInput$.setInterval(intervalInMileSeconds); } - private _simulateEventTouch (eventMouse: EventMouse): void { + private _simulateEventTouch$ (eventMouse: EventMouse): void { const eventType = pointerEventTypeMap[eventMouse.type]; const touchID = 0; const touch = touchManager.getOrCreateTouch(touchID, eventMouse.getLocationX(), eventMouse.getLocationY()); @@ -324,21 +324,21 @@ export class Input { if (eventType === InputEventType.TOUCH_END) { touchManager.releaseTouch(touchID); } - this._dispatchOrPushEventTouch(eventTouch, this._eventTouchList); + this._dispatchOrPushEventTouch$(eventTouch, this._eventTouchList$); } /** * @engineInternal */ public _registerEventDispatcher (eventDispatcher: IEventDispatcher): void { - this._eventDispatcherList.push(eventDispatcher); - this._eventDispatcherList.sort((a, b): number => b.priority - a.priority); + this._eventDispatcherList$.push(eventDispatcher); + this._eventDispatcherList$.sort((a, b): number => b.priority - a.priority); } - private _emitEvent (event: Event): void { - const length = this._eventDispatcherList.length; + private _emitEvent$ (event: Event): void { + const length = this._eventDispatcherList$.length; for (let i = 0; i < length; ++i) { - const dispatcher = this._eventDispatcherList[i]; + const dispatcher = this._eventDispatcherList$[i]; try { if (!dispatcher.dispatchEvent(event)) { break; @@ -351,106 +351,106 @@ export class Input { } } - private _registerEvent (): void { + private _registerEvent$ (): void { if (sys.hasFeature(sys.Feature.INPUT_TOUCH)) { - const eventTouchList = this._eventTouchList; - this._touchInput.on(InputEventType.TOUCH_START, (event): void => { - this._dispatchOrPushEventTouch(event, eventTouchList); + const eventTouchList = this._eventTouchList$; + this._touchInput$.on(InputEventType.TOUCH_START, (event): void => { + this._dispatchOrPushEventTouch$(event, eventTouchList); }); - this._touchInput.on(InputEventType.TOUCH_MOVE, (event): void => { - this._dispatchOrPushEventTouch(event, eventTouchList); + this._touchInput$.on(InputEventType.TOUCH_MOVE, (event): void => { + this._dispatchOrPushEventTouch$(event, eventTouchList); }); - this._touchInput.on(InputEventType.TOUCH_END, (event): void => { - this._dispatchOrPushEventTouch(event, eventTouchList); + this._touchInput$.on(InputEventType.TOUCH_END, (event): void => { + this._dispatchOrPushEventTouch$(event, eventTouchList); }); - this._touchInput.on(InputEventType.TOUCH_CANCEL, (event): void => { - this._dispatchOrPushEventTouch(event, eventTouchList); + this._touchInput$.on(InputEventType.TOUCH_CANCEL, (event): void => { + this._dispatchOrPushEventTouch$(event, eventTouchList); }); } if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) { - const eventMouseList = this._eventMouseList; - this._mouseInput.on(InputEventType.MOUSE_DOWN, (event): void => { - this._needSimulateTouchMoveEvent = true; - this._simulateEventTouch(event); - this._dispatchOrPushEvent(event, eventMouseList); + const eventMouseList = this._eventMouseList$; + this._mouseInput$.on(InputEventType.MOUSE_DOWN, (event): void => { + this._needSimulateTouchMoveEvent$ = true; + this._simulateEventTouch$(event); + this._dispatchOrPushEvent$(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_MOVE, (event): void => { - if (this._needSimulateTouchMoveEvent) { - this._simulateEventTouch(event); + this._mouseInput$.on(InputEventType.MOUSE_MOVE, (event): void => { + if (this._needSimulateTouchMoveEvent$) { + this._simulateEventTouch$(event); } - this._dispatchOrPushEvent(event, eventMouseList); + this._dispatchOrPushEvent$(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_UP, (event): void => { - this._needSimulateTouchMoveEvent = false; - this._simulateEventTouch(event); - this._dispatchOrPushEvent(event, eventMouseList); + this._mouseInput$.on(InputEventType.MOUSE_UP, (event): void => { + this._needSimulateTouchMoveEvent$ = false; + this._simulateEventTouch$(event); + this._dispatchOrPushEvent$(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_WHEEL, (event): void => { - this._dispatchOrPushEvent(event, eventMouseList); + this._mouseInput$.on(InputEventType.MOUSE_WHEEL, (event): void => { + this._dispatchOrPushEvent$(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_LEAVE, (event): void => { - this._dispatchOrPushEvent(event, eventMouseList); + this._mouseInput$.on(InputEventType.MOUSE_LEAVE, (event): void => { + this._dispatchOrPushEvent$(event, eventMouseList); }); - this._mouseInput.on(InputEventType.MOUSE_ENTER, (event): void => { - this._dispatchOrPushEvent(event, eventMouseList); + this._mouseInput$.on(InputEventType.MOUSE_ENTER, (event): void => { + this._dispatchOrPushEvent$(event, eventMouseList); }); } if (sys.hasFeature(sys.Feature.EVENT_KEYBOARD)) { - const eventKeyboardList = this._eventKeyboardList; - this._keyboardInput.on(InputEventType.KEY_DOWN, (event): void => { - this._dispatchOrPushEvent(event, eventKeyboardList); + const eventKeyboardList = this._eventKeyboardList$; + this._keyboardInput$.on(InputEventType.KEY_DOWN, (event): void => { + this._dispatchOrPushEvent$(event, eventKeyboardList); }); - this._keyboardInput.on(InputEventType.KEY_PRESSING, (event): void => { - this._dispatchOrPushEvent(event, eventKeyboardList); + this._keyboardInput$.on(InputEventType.KEY_PRESSING, (event): void => { + this._dispatchOrPushEvent$(event, eventKeyboardList); }); - this._keyboardInput.on(InputEventType.KEY_UP, (event): void => { - this._dispatchOrPushEvent(event, eventKeyboardList); + this._keyboardInput$.on(InputEventType.KEY_UP, (event): void => { + this._dispatchOrPushEvent$(event, eventKeyboardList); }); } if (sys.hasFeature(sys.Feature.EVENT_ACCELEROMETER)) { - const eventAccelerationList = this._eventAccelerationList; - this._accelerometerInput.on(InputEventType.DEVICEMOTION, (event): void => { - this._dispatchOrPushEvent(event, eventAccelerationList); + const eventAccelerationList = this._eventAccelerationList$; + this._accelerometerInput$.on(InputEventType.DEVICEMOTION, (event): void => { + this._dispatchOrPushEvent$(event, eventAccelerationList); }); } if (sys.hasFeature(sys.Feature.EVENT_GAMEPAD)) { - const eventGamepadList = this._eventGamepadList; + const eventGamepadList = this._eventGamepadList$; GamepadInputDevice._on(InputEventType.GAMEPAD_CHANGE, (event): void => { - this._dispatchOrPushEvent(event, eventGamepadList); + this._dispatchOrPushEvent$(event, eventGamepadList); }); GamepadInputDevice._on(InputEventType.GAMEPAD_INPUT, (event): void => { - this._dispatchOrPushEvent(event, eventGamepadList); + this._dispatchOrPushEvent$(event, eventGamepadList); }); GamepadInputDevice._on(InputEventType.HANDLE_POSE_INPUT, (event): void => { - this._dispatchOrPushEvent(event, eventGamepadList); + this._dispatchOrPushEvent$(event, eventGamepadList); }); } if (sys.hasFeature(sys.Feature.EVENT_HANDLE)) { - const eventHandleList = this._eventHandleList; - this._handleInput._on(InputEventType.HANDLE_INPUT, (event): void => { - this._dispatchOrPushEvent(event, eventHandleList); + const eventHandleList = this._eventHandleList$; + this._handleInput$._on(InputEventType.HANDLE_INPUT, (event): void => { + this._dispatchOrPushEvent$(event, eventHandleList); }); - this._handleInput._on(InputEventType.HANDLE_POSE_INPUT, (event): void => { - this._dispatchOrPushEvent(event, eventHandleList); + this._handleInput$._on(InputEventType.HANDLE_POSE_INPUT, (event): void => { + this._dispatchOrPushEvent$(event, eventHandleList); }); } if (sys.hasFeature(sys.Feature.EVENT_HMD)) { - const eventHMDList = this._eventHMDList; - this._hmdInput._on(InputEventType.HMD_POSE_INPUT, (event): void => { - this._dispatchOrPushEvent(event, eventHMDList); + const eventHMDList = this._eventHMDList$; + this._hmdInput$._on(InputEventType.HMD_POSE_INPUT, (event): void => { + this._dispatchOrPushEvent$(event, eventHMDList); }); } if (sys.hasFeature(sys.Feature.EVENT_HANDHELD)) { - const eventHandheldList = this._eventHandheldList; - this._handheldInput._on(InputEventType.HANDHELD_POSE_INPUT, (event): void => { - this._dispatchOrPushEvent(event, eventHandheldList); + const eventHandheldList = this._eventHandheldList$; + this._handheldInput$._on(InputEventType.HANDHELD_POSE_INPUT, (event): void => { + this._dispatchOrPushEvent$(event, eventHandheldList); }); } } @@ -459,31 +459,31 @@ export class Input { * @engineInternal */ public _clearEvents (): void { - this._eventMouseList.length = 0; - this._eventTouchList.length = 0; - this._eventKeyboardList.length = 0; - this._eventAccelerationList.length = 0; - this._eventGamepadList.length = 0; - this._eventHandleList.length = 0; - this._eventHMDList.length = 0; + this._eventMouseList$.length = 0; + this._eventTouchList$.length = 0; + this._eventKeyboardList$.length = 0; + this._eventAccelerationList$.length = 0; + this._eventGamepadList$.length = 0; + this._eventHandleList$.length = 0; + this._eventHMDList$.length = 0; } - private _dispatchOrPushEvent (event: Event, eventList: Event[]): void { - if (this._dispatchImmediately) { - this._emitEvent(event); + private _dispatchOrPushEvent$ (event: Event, eventList: Event[]): void { + if (this._dispatchImmediately$) { + this._emitEvent$(event); } else { eventList.push(event); } } - private _dispatchOrPushEventTouch (eventTouch: EventTouch, touchEventList: EventTouch[]): void { - if (this._dispatchImmediately) { + private _dispatchOrPushEventTouch$ (eventTouch: EventTouch, touchEventList: EventTouch[]): void { + if (this._dispatchImmediately$) { const touches = eventTouch.getTouches(); const touchesLength = touches.length; for (let i = 0; i < touchesLength; ++i) { eventTouch.touch = touches[i]; eventTouch.propagationStopped = eventTouch.propagationImmediateStopped = false; - this._emitEvent(eventTouch); + this._emitEvent$(eventTouch); } } else { touchEventList.push(eventTouch); @@ -494,28 +494,28 @@ export class Input { * @engineInternal */ public _frameDispatchEvents (): void { - const eventHMDList = this._eventHMDList; + const eventHMDList = this._eventHMDList$; // TODO: culling event queue for (let i = 0, length = eventHMDList.length; i < length; ++i) { const eventHMD = eventHMDList[i]; - this._emitEvent(eventHMD); + this._emitEvent$(eventHMD); } - const eventHandheldList = this._eventHandheldList; + const eventHandheldList = this._eventHandheldList$; // TODO: culling event queue for (let i = 0, length = eventHandheldList.length; i < length; ++i) { const eventHandheld = eventHandheldList[i]; - this._emitEvent(eventHandheld); + this._emitEvent$(eventHandheld); } - const eventMouseList = this._eventMouseList; + const eventMouseList = this._eventMouseList$; // TODO: culling event queue for (let i = 0, length = eventMouseList.length; i < length; ++i) { const eventMouse = eventMouseList[i]; - this._emitEvent(eventMouse); + this._emitEvent$(eventMouse); } - const eventTouchList = this._eventTouchList; + const eventTouchList = this._eventTouchList$; // TODO: culling event queue for (let i = 0, length = eventTouchList.length; i < length; ++i) { const eventTouch = eventTouchList[i]; @@ -524,36 +524,36 @@ export class Input { for (let j = 0; j < touchesLength; ++j) { eventTouch.touch = touches[j]; eventTouch.propagationStopped = eventTouch.propagationImmediateStopped = false; - this._emitEvent(eventTouch); + this._emitEvent$(eventTouch); } } - const eventKeyboardList = this._eventKeyboardList; + const eventKeyboardList = this._eventKeyboardList$; // TODO: culling event queue for (let i = 0, length = eventKeyboardList.length; i < length; ++i) { const eventKeyboard = eventKeyboardList[i]; - this._emitEvent(eventKeyboard); + this._emitEvent$(eventKeyboard); } - const eventAccelerationList = this._eventAccelerationList; + const eventAccelerationList = this._eventAccelerationList$; // TODO: culling event queue for (let i = 0, length = eventAccelerationList.length; i < length; ++i) { const eventAcceleration = eventAccelerationList[i]; - this._emitEvent(eventAcceleration); + this._emitEvent$(eventAcceleration); } - const eventGamepadList = this._eventGamepadList; + const eventGamepadList = this._eventGamepadList$; // TODO: culling event queue for (let i = 0, length = eventGamepadList.length; i < length; ++i) { const eventGamepad = eventGamepadList[i]; - this._emitEvent(eventGamepad); + this._emitEvent$(eventGamepad); } - const eventHandleList = this._eventHandleList; + const eventHandleList = this._eventHandleList$; // TODO: culling event queue for (let i = 0, length = eventHandleList.length; i < length; ++i) { const eventHandle = eventHandleList[i]; - this._emitEvent(eventHandle); + this._emitEvent$(eventHandle); } this._clearEvents(); @@ -569,8 +569,8 @@ export class Input { * * @example * ``` - * input.on(Input.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); - * input.off(Input.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * input.on(InputEventType.DEVICEMOTION, this.onDeviceMotionEvent, this); + * input.off(InputEventType.DEVICEMOTION, this.onDeviceMotionEvent, this); * ``` */ export const input = new Input(); diff --git a/cocos/input/types/event/event-keyboard.ts b/cocos/input/types/event/event-keyboard.ts index 60bdf969ee4..c39960cf427 100644 --- a/cocos/input/types/event/event-keyboard.ts +++ b/cocos/input/types/event/event-keyboard.ts @@ -54,13 +54,13 @@ export class EventKeyboard extends Event { */ public rawEvent?: KeyboardEvent; - private declare _isPressed: boolean; + private declare _isPressed$: boolean; /** * @en Indicates whether the current key is being pressed * @zh 表示当前按键是否正在被按下 */ public get isPressed (): boolean { - return this._isPressed; + return this._isPressed$; } /** @@ -81,7 +81,7 @@ export class EventKeyboard extends Event { eventType = isPressed ? SystemEventType.KEY_DOWN : SystemEventType.KEY_UP; } super(eventType, bubbles); - this._isPressed = eventType !== SystemEventType.KEY_UP; + this._isPressed$ = eventType !== SystemEventType.KEY_UP; if (typeof keyCode === 'number') { this.keyCode = keyCode; diff --git a/cocos/input/types/event/event-touch.ts b/cocos/input/types/event/event-touch.ts index 0c931151d40..48e2da31132 100644 --- a/cocos/input/types/event/event-touch.ts +++ b/cocos/input/types/event/event-touch.ts @@ -74,11 +74,11 @@ export class EventTouch extends Event { */ public preventSwallow = false; - private declare _eventCode: SystemEventTypeUnion; // deprecated since v3.3 + private declare _eventCode$: SystemEventTypeUnion; // deprecated since v3.3 - private declare _touches: Touch[]; + private declare _touches$: Touch[]; - private declare _allTouches: Touch[]; + private declare _allTouches$: Touch[]; /** * @param touches - An array of current touches @@ -87,9 +87,9 @@ export class EventTouch extends Event { */ constructor (changedTouches: Touch[], bubbles: boolean, eventType: SystemEventTypeUnion, touches: Touch[] = []) { super(eventType, bubbles); - this._eventCode = eventType; - this._touches = changedTouches || []; - this._allTouches = touches; + this._eventCode$ = eventType; + this._touches$ = changedTouches || []; + this._allTouches$ = touches; } /** @@ -99,7 +99,7 @@ export class EventTouch extends Event { * @deprecated since v3.3, please use EventTouch.prototype.type instead. */ public getEventCode (): string { - return this._eventCode; + return this._eventCode$; } /** @@ -109,7 +109,7 @@ export class EventTouch extends Event { * 如果需要获取全部手指的信息,请使用 `getAllTouches`。 */ public getTouches (): Touch[] { - return this._touches; + return this._touches$; } /** @@ -118,7 +118,7 @@ export class EventTouch extends Event { * 注意:如果手指行为是 touch end,这个时候列表是没有该手指信息的。如需知道该手指信息,可通过 `getTouches` 获取识别。 */ public getAllTouches (): Touch[] { - return this._allTouches; + return this._allTouches$; } /** diff --git a/cocos/input/types/touch.ts b/cocos/input/types/touch.ts index 2e0cc238702..e49b9d69deb 100644 --- a/cocos/input/types/touch.ts +++ b/cocos/input/types/touch.ts @@ -31,15 +31,15 @@ const _vec2 = new Vec2(); * @zh 封装了触点相关的信息。 */ export class Touch { - private _point: Vec2 = new Vec2(); - private _prevPoint: Vec2 = new Vec2(); - private _lastModified = 0; + private _point$: Vec2 = new Vec2(); + private _prevPoint$: Vec2 = new Vec2(); + private _lastModified$ = 0; private _id = 0; - private _startPoint: Vec2 = new Vec2(); - private _startPointCaptured = false; + private _startPoint$: Vec2 = new Vec2(); + private _startPointCaptured$ = false; get lastModified (): number { - return this._lastModified; + return this._lastModified$; } /** @@ -61,7 +61,7 @@ export class Touch { out = new Vec2(); } - out.set(this._point.x, this._point.y); + out.set(this._point$.x, this._point$.y); return out; } @@ -70,7 +70,7 @@ export class Touch { * @zh 获取当前触点 X 轴位置。 */ public getLocationX (): number { - return this._point.x; + return this._point$.x; } /** @@ -78,7 +78,7 @@ export class Touch { * @zh 获取当前触点 Y 轴位置。 */ public getLocationY (): number { - return this._point.y; + return this._point$.y; } /** @@ -91,7 +91,7 @@ export class Touch { out = new Vec2(); } - out.set(this._point.x, this._point.y); + out.set(this._point$.x, this._point$.y); cclegacy.view._convertToUISpace(out); return out; } @@ -102,7 +102,7 @@ export class Touch { */ public getUILocationX (): number { const viewport = cclegacy.view.getViewportRect(); - return (this._point.x - viewport.x) / cclegacy.view.getScaleX(); + return (this._point$.x - viewport.x) / cclegacy.view.getScaleX(); } /** @@ -111,7 +111,7 @@ export class Touch { */ public getUILocationY (): number { const viewport = cclegacy.view.getViewportRect(); - return (this._point.y - viewport.y) / cclegacy.view.getScaleY(); + return (this._point$.y - viewport.y) / cclegacy.view.getScaleY(); } /** @@ -124,7 +124,7 @@ export class Touch { out = new Vec2(); } - out.set(this._prevPoint.x, this._prevPoint.y); + out.set(this._prevPoint$.x, this._prevPoint$.y); return out; } @@ -138,7 +138,7 @@ export class Touch { out = new Vec2(); } - out.set(this._prevPoint.x, this._prevPoint.y); + out.set(this._prevPoint$.x, this._prevPoint$.y); cclegacy.view._convertToUISpace(out); return out; } @@ -153,7 +153,7 @@ export class Touch { out = new Vec2(); } - out.set(this._startPoint.x, this._startPoint.y); + out.set(this._startPoint$.x, this._startPoint$.y); return out; } @@ -167,7 +167,7 @@ export class Touch { out = new Vec2(); } - out.set(this._startPoint.x, this._startPoint.y); + out.set(this._startPoint$.x, this._startPoint$.y); cclegacy.view._convertToUISpace(out); return out; } @@ -182,8 +182,8 @@ export class Touch { out = new Vec2(); } - out.set(this._point); - out.subtract(this._prevPoint); + out.set(this._point$); + out.subtract(this._prevPoint$); return out; } @@ -197,8 +197,8 @@ export class Touch { out = new Vec2(); } - _vec2.set(this._point); - _vec2.subtract(this._prevPoint); + _vec2.set(this._point$); + _vec2.subtract(this._prevPoint$); out.set(cclegacy.view.getScaleX() as number, cclegacy.view.getScaleY() as number); Vec2.divide(out, _vec2, out); return out; @@ -214,7 +214,7 @@ export class Touch { out = new Vec2(); } - out.set(this._point.x, cclegacy.view._designResolutionSize.height - this._point.y); + out.set(this._point$.x, cclegacy.view._designResolutionSize.height - this._point$.y); return out; } @@ -228,7 +228,7 @@ export class Touch { out = new Vec2(); } - out.set(this._prevPoint.x, cclegacy.view._designResolutionSize.height - this._prevPoint.y); + out.set(this._prevPoint$.x, cclegacy.view._designResolutionSize.height - this._prevPoint$.y); return out; } @@ -242,7 +242,7 @@ export class Touch { out = new Vec2(); } - out.set(this._startPoint.x, cclegacy.view._designResolutionSize.height - this._startPoint.y); + out.set(this._startPoint$.x, cclegacy.view._designResolutionSize.height - this._startPoint$.y); return out; } @@ -262,13 +262,13 @@ export class Touch { * @param y - y position of the touch point */ public setTouchInfo (id: number = 0, x: number = 0, y: number = 0): void { - this._prevPoint = this._point; - this._point = new Vec2(x || 0, y || 0); + this._prevPoint$ = this._point$; + this._point$ = new Vec2(x || 0, y || 0); this._id = id; - if (!this._startPointCaptured) { - this._startPoint = new Vec2(this._point); + if (!this._startPointCaptured$) { + this._startPoint$ = new Vec2(this._point$); // cc.view._convertToUISpace(this._startPoint); - this._startPointCaptured = true; + this._startPointCaptured$ = true; } } @@ -289,13 +289,13 @@ export class Touch { public setPoint (x: number | Vec2, y?: number): void { if (typeof x === 'object') { - this._point.x = x.x; - this._point.y = x.y; + this._point$.x = x.x; + this._point$.y = x.y; } else { - this._point.x = x || 0; - this._point.y = y || 0; + this._point$.x = x || 0; + this._point$.y = y || 0; } - this._lastModified = cclegacy.game.frameStartTime; + this._lastModified$ = cclegacy.game.frameStartTime; } /** @@ -315,11 +315,11 @@ export class Touch { public setPrevPoint (x: number | Vec2, y?: number): void { if (typeof x === 'object') { - this._prevPoint = new Vec2(x.x, x.y); + this._prevPoint$ = new Vec2(x.x, x.y); } else { - this._prevPoint = new Vec2(x || 0, y || 0); + this._prevPoint$ = new Vec2(x || 0, y || 0); } - this._lastModified = cclegacy.game.frameStartTime; + this._lastModified$ = cclegacy.game.frameStartTime; } /** diff --git a/cocos/misc/camera-component.ts b/cocos/misc/camera-component.ts index 1bd819499e9..e74b42b8d3d 100644 --- a/cocos/misc/camera-component.ts +++ b/cocos/misc/camera-component.ts @@ -31,7 +31,7 @@ import { Component } from '../scene-graph'; import { Color, Rect, toRadian, Vec3, cclegacy, geometry, Enum } from '../core'; import { CAMERA_DEFAULT_MASK } from '../rendering/define'; import { scene } from '../render-scene'; -import { SKYBOX_FLAG, CameraProjection, CameraFOVAxis, CameraAperture, CameraISO, CameraShutter, +import { SkyBoxFlagValue, CameraProjection, CameraFOVAxis, CameraAperture, CameraISO, CameraShutter, CameraType, TrackingType } from '../render-scene/scene/camera'; import { Node } from '../scene-graph/node'; import { Layers } from '../scene-graph/layers'; @@ -59,7 +59,7 @@ export const ClearFlag = Enum({ * @en Clear the screen with [[SceneGlobals.skybox]], will clear the depth and stencil buffer at the same time. * @zh 使用指定天空盒 [[SceneGlobals.skybox]] 清屏,会同时清理深度和蒙版缓冲。 */ - SKYBOX: SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL, + SKYBOX: SkyBoxFlagValue.VALUE | ClearFlagBit.DEPTH_STENCIL, /** * @en Clear the screen with the given [[Camera.clearColor]], will clear the depth and stencil buffer at the same time. * @zh 使用指定的相机清屏颜色 [[Camera.clearColor]] 来清屏,会同时清理将深度和蒙版缓冲。 @@ -89,6 +89,10 @@ export declare namespace Camera { export type ISO = EnumAlias; } +export enum CameraEvent { + TARGET_TEXTURE_CHANGE = 'tex-change', +} + /** * @en The Camera Component. * @zh 相机组件。 @@ -132,7 +136,7 @@ export class Camera extends Component { * @en The event for target texture changing. * @zh 目标贴图修改的事件。 */ - public static TARGET_TEXTURE_CHANGE = 'tex-change'; + public static TARGET_TEXTURE_CHANGE = CameraEvent.TARGET_TEXTURE_CHANGE; @serializable protected _projection = ProjectionType.PERSPECTIVE; @@ -494,7 +498,7 @@ export class Camera extends Component { this._camera.changeTargetWindow(EDITOR ? cclegacy.director.root.tempWindow : null); this._camera.isWindowSize = true; } - this.node.emit(Camera.TARGET_TEXTURE_CHANGE, this); + this.node.emit(CameraEvent.TARGET_TEXTURE_CHANGE, this); } @tooltip('i18n:camera.use_postprocess') diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index f96ebdd5b63..3f004f87160 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -51,6 +51,7 @@ import { TransformBit } from '../scene-graph/node-enum'; import { Camera } from '../render-scene/scene'; import { ParticleCuller } from './particle-culler'; import { NoiseModule } from './animator/noise-module'; +import { director, DirectorEvent } from '../game/director'; const _world_mat = new Mat4(); const _world_rol = new Quat(); @@ -1083,7 +1084,7 @@ export class ParticleSystem extends ModelRenderer { this._trailModule._detachFromScene(); } } - cclegacy.director.off(cclegacy.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); + director.off(DirectorEvent.BEFORE_COMMIT, this.beforeRender, this); // this._system.remove(this); this.processor.onDestroy(); if (this._trailModule) this._trailModule.destroy(); @@ -1096,7 +1097,7 @@ export class ParticleSystem extends ModelRenderer { protected onEnable (): void { super.onEnable(); - cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); + director.on(DirectorEvent.BEFORE_COMMIT, this.beforeRender, this); if (this.playOnAwake && !EDITOR_NOT_IN_PREVIEW) { this.play(); } @@ -1104,7 +1105,7 @@ export class ParticleSystem extends ModelRenderer { if (this._trailModule) this._trailModule.onEnable(); } protected onDisable (): void { - cclegacy.director.off(cclegacy.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); + director.off(DirectorEvent.BEFORE_COMMIT, this.beforeRender, this); this.processor.onDisable(); if (this._trailModule) this._trailModule.onDisable(); if (this._boundingBox) { diff --git a/cocos/particle/particle-utils.ts b/cocos/particle/particle-utils.ts index 7e882213656..6985787d64e 100644 --- a/cocos/particle/particle-utils.ts +++ b/cocos/particle/particle-utils.ts @@ -24,7 +24,7 @@ import { instantiate } from '../serialization'; import { CCObject, Pool } from '../core'; -import { Director, director } from '../game/director'; +import { director, DirectorEvent } from '../game/director'; import { Node } from '../scene-graph'; import { ParticleSystem } from './particle-system'; @@ -39,7 +39,7 @@ export class ParticleUtils { */ public static instantiate (prefab: any): CCObject { if (!this.registeredSceneEvent) { - director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.onSceneUnload, this); + director.on(DirectorEvent.BEFORE_SCENE_LAUNCH, this.onSceneUnload, this); this.registeredSceneEvent = true; } const uuid = prefab._uuid as string; diff --git a/cocos/physics-2d/framework/physics-system.ts b/cocos/physics-2d/framework/physics-system.ts index 5f0a1de17de..1007ff3fdf3 100644 --- a/cocos/physics-2d/framework/physics-system.ts +++ b/cocos/physics-2d/framework/physics-system.ts @@ -23,19 +23,19 @@ */ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; -import { System, Vec2, IVec2Like, Rect, Eventify, Enum, Settings, settings, cclegacy } from '../../core'; +import { System, Vec2, IVec2Like, Rect, Eventify, Enum, Settings, settings, cclegacy, SettingsCategory } from '../../core'; import { createPhysicsWorld, selector, IPhysicsSelector } from './physics-selector'; import { DelayEvent } from './physics-internal-types'; import { ICollisionMatrix } from '../../physics/framework/physics-config'; import { CollisionMatrix } from '../../physics/framework/collision-matrix'; -import { ERaycast2DType, RaycastResult2D, PHYSICS_2D_PTM_RATIO, PhysicsGroup } from './physics-types'; +import { ERaycast2DType, RaycastResult2D, PHYSICS_2D_PTM_RATIO, PhysicsGroup2D } from './physics-types'; import { Collider2D } from './components/colliders/collider-2d'; -import { director, Director } from '../../game'; +import { director, DirectorEvent } from '../../game'; import type { IPhysicsWorld } from '../spec/i-physics-world'; let instance: PhysicsSystem2D | null = null; -cclegacy.internal.PhysicsGroup2D = PhysicsGroup; +cclegacy.internal.PhysicsGroup2D = PhysicsGroup2D; export class PhysicsSystem2D extends Eventify(System) { /** @@ -187,8 +187,8 @@ export class PhysicsSystem2D extends Eventify(System) { * @zh * 获取预定义的物理分组。 */ - public static get PhysicsGroup (): typeof PhysicsGroup { - return PhysicsGroup; + public static get PhysicsGroup (): typeof PhysicsGroup2D { + return PhysicsGroup2D; } /** @@ -230,16 +230,16 @@ export class PhysicsSystem2D extends Eventify(System) { private constructor () { super(); - const gravity = settings.querySettings(Settings.Category.PHYSICS, 'gravity'); + const gravity = settings.querySettings(SettingsCategory.PHYSICS, 'gravity'); if (gravity) { Vec2.copy(this._gravity, gravity as IVec2Like); this._gravity.multiplyScalar(PHYSICS_2D_PTM_RATIO); } - this._allowSleep = settings.querySettings(Settings.Category.PHYSICS, 'allowSleep') ?? this._allowSleep; - this._fixedTimeStep = settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep') ?? this._fixedTimeStep; - this._maxSubSteps = settings.querySettings(Settings.Category.PHYSICS, 'maxSubSteps') ?? this._maxSubSteps; - this._autoSimulation = settings.querySettings(Settings.Category.PHYSICS, 'autoSimulation') ?? this._autoSimulation; - const collisionMatrix = settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix'); + this._allowSleep = settings.querySettings(SettingsCategory.PHYSICS, 'allowSleep') ?? this._allowSleep; + this._fixedTimeStep = settings.querySettings(SettingsCategory.PHYSICS, 'fixedTimeStep') ?? this._fixedTimeStep; + this._maxSubSteps = settings.querySettings(SettingsCategory.PHYSICS, 'maxSubSteps') ?? this._maxSubSteps; + this._autoSimulation = settings.querySettings(SettingsCategory.PHYSICS, 'autoSimulation') ?? this._autoSimulation; + const collisionMatrix = settings.querySettings(SettingsCategory.PHYSICS, 'collisionMatrix'); if (collisionMatrix) { for (const i in collisionMatrix) { const bit = parseInt(i); @@ -248,12 +248,12 @@ export class PhysicsSystem2D extends Eventify(System) { } } - const collisionGroups = settings.querySettings>(Settings.Category.PHYSICS, 'collisionGroups'); + const collisionGroups = settings.querySettings>(SettingsCategory.PHYSICS, 'collisionGroups'); if (collisionGroups) { const cg = collisionGroups; if (cg instanceof Array) { - cg.forEach((v): void => { PhysicsGroup[v.name] = 1 << v.index; }); - Enum.update(PhysicsGroup); + cg.forEach((v): void => { PhysicsGroup2D[v.name] = 1 << v.index; }); + Enum.update(PhysicsGroup2D); } } @@ -279,7 +279,7 @@ export class PhysicsSystem2D extends Eventify(System) { return; } - director.emit(Director.EVENT_BEFORE_PHYSICS); + director.emit(DirectorEvent.BEFORE_PHYSICS); this.physicsWorld.syncSceneToPhysics(); @@ -310,7 +310,7 @@ export class PhysicsSystem2D extends Eventify(System) { } this._steping = false; - director.emit(Director.EVENT_AFTER_PHYSICS); + director.emit(DirectorEvent.AFTER_PHYSICS); } // eslint-disable-next-line @typescript-eslint/ban-types @@ -383,4 +383,4 @@ export class PhysicsSystem2D extends Eventify(System) { } } -director.once(Director.EVENT_INIT, (): void => { PhysicsSystem2D.constructAndRegister(); }); +director.once(DirectorEvent.INIT, (): void => { PhysicsSystem2D.constructAndRegister(); }); diff --git a/cocos/physics-2d/framework/physics-types.ts b/cocos/physics-2d/framework/physics-types.ts index f8b2dccdf29..95ed8e56628 100644 --- a/cocos/physics-2d/framework/physics-types.ts +++ b/cocos/physics-2d/framework/physics-types.ts @@ -78,10 +78,10 @@ export enum EJoint2DType { } Enum(EJoint2DType); -export enum PhysicsGroup { +export enum PhysicsGroup2D { DEFAULT = 1, } -Enum(PhysicsGroup); +Enum(PhysicsGroup2D); /** * @en Enum for ERaycast2DType. diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index e83c672d0aa..7c221a98993 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -23,9 +23,9 @@ */ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; -import { Vec3, RecyclePool, Enum, System, cclegacy, Settings, settings, geometry, warn, IQuatLike, IVec3Like } from '../../core'; +import { Vec3, RecyclePool, Enum, System, cclegacy, settings, geometry, warn, IQuatLike, IVec3Like, SettingsCategory } from '../../core'; import { IPhysicsWorld, IRaycastOptions } from '../spec/i-physics-world'; -import { director, Director, game } from '../../game'; +import { director, Director, DirectorEvent, game } from '../../game'; import { PhysicsMaterial } from './assets/physics-material'; import { PhysicsRayResult, PhysicsLineStripCastResult } from './physics-ray-result'; import { IPhysicsConfig, ICollisionMatrix } from './physics-config'; @@ -228,7 +228,7 @@ export class PhysicsSystem extends System implements IWorldInitData { return Promise.resolve(); } - const userMaterial = settings.querySettings(Settings.Category.PHYSICS, 'defaultMaterial'); + const userMaterial = settings.querySettings(SettingsCategory.PHYSICS, 'defaultMaterial'); if (!userMaterial) { //use built-in default physics material this.setDefaultPhysicsMaterial(builtinMaterial); return Promise.resolve(); @@ -361,7 +361,7 @@ export class PhysicsSystem extends System implements IWorldInitData { if (this._autoSimulation) { this._subStepCount = 0; this._accumulator += deltaTime; - director.emit(Director.EVENT_BEFORE_PHYSICS); + director.emit(DirectorEvent.BEFORE_PHYSICS); while (this._subStepCount < this._maxSubSteps) { if (this._accumulator >= this._fixedTimeStep) { this.physicsWorld.syncSceneToPhysics(); @@ -375,7 +375,7 @@ export class PhysicsSystem extends System implements IWorldInitData { break; } } - director.emit(Director.EVENT_AFTER_PHYSICS); + director.emit(DirectorEvent.AFTER_PHYSICS); } } @@ -386,27 +386,27 @@ export class PhysicsSystem extends System implements IWorldInitData { * 重置物理配置。 */ resetConfiguration (config?: IPhysicsConfig): void { - const allowSleep = config ? config.allowSleep : settings.querySettings(Settings.Category.PHYSICS, 'allowSleep'); + const allowSleep = config ? config.allowSleep : settings.querySettings(SettingsCategory.PHYSICS, 'allowSleep'); if (typeof allowSleep === 'boolean') this._allowSleep = allowSleep; - const fixedTimeStep = config ? config.fixedTimeStep : settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep'); + const fixedTimeStep = config ? config.fixedTimeStep : settings.querySettings(SettingsCategory.PHYSICS, 'fixedTimeStep'); if (typeof fixedTimeStep === 'number') this._fixedTimeStep = fixedTimeStep; - const maxSubSteps = config ? config.maxSubSteps : settings.querySettings(Settings.Category.PHYSICS, 'maxSubSteps'); + const maxSubSteps = config ? config.maxSubSteps : settings.querySettings(SettingsCategory.PHYSICS, 'maxSubSteps'); if (typeof maxSubSteps === 'number') this._maxSubSteps = maxSubSteps; - const sleepThreshold = config ? config.sleepThreshold : settings.querySettings(Settings.Category.PHYSICS, 'sleepThreshold'); + const sleepThreshold = config ? config.sleepThreshold : settings.querySettings(SettingsCategory.PHYSICS, 'sleepThreshold'); if (typeof sleepThreshold === 'number') this._sleepThreshold = sleepThreshold; - const autoSimulation = config ? config.autoSimulation : settings.querySettings(Settings.Category.PHYSICS, 'autoSimulation'); + const autoSimulation = config ? config.autoSimulation : settings.querySettings(SettingsCategory.PHYSICS, 'autoSimulation'); if (typeof autoSimulation === 'boolean') this.autoSimulation = autoSimulation; - const gravity = config ? config.gravity : settings.querySettings(Settings.Category.PHYSICS, 'gravity'); + const gravity = config ? config.gravity : settings.querySettings(SettingsCategory.PHYSICS, 'gravity'); if (gravity) Vec3.copy(this._gravity, gravity); - const collisionMatrix = config ? config.collisionMatrix : settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix'); + const collisionMatrix = config ? config.collisionMatrix : settings.querySettings(SettingsCategory.PHYSICS, 'collisionMatrix'); if (collisionMatrix) { for (const i in collisionMatrix) { this.collisionMatrix[`${1 << parseInt(i)}`] = collisionMatrix[i]; } } - const collisionGroups = config ? config.collisionGroups : settings.querySettings>(Settings.Category.PHYSICS, 'collisionGroups'); + const collisionGroups = config ? config.collisionGroups : settings.querySettings>(SettingsCategory.PHYSICS, 'collisionGroups'); if (collisionGroups) { const cg = collisionGroups; if (cg instanceof Array) { @@ -867,7 +867,7 @@ export class PhysicsSystem extends System implements IWorldInitData { * 预先加载模块的情况下,会自动执行。 */ static constructAndRegister (): void { - const enabled = settings.querySettings(Settings.Category.PHYSICS, 'enabled') ?? true; + const enabled = settings.querySettings(SettingsCategory.PHYSICS, 'enabled') ?? true; if (!enabled) { return; } if (!PhysicsSystem._instance) { // Construct physics world and physics system only once @@ -886,4 +886,4 @@ export class PhysicsSystem extends System implements IWorldInitData { * By registering the initialization event, the system can be automatically * constructed and registered when the module is pre-loaded */ -director.once(Director.EVENT_INIT, (): void => { PhysicsSystem.constructAndRegister(); }); +director.once(DirectorEvent.INIT, (): void => { PhysicsSystem.constructAndRegister(); }); diff --git a/cocos/profiler/profiler.ts b/cocos/profiler/profiler.ts index 6d56b6b1b94..d379f5c57eb 100644 --- a/cocos/profiler/profiler.ts +++ b/cocos/profiler/profiler.ts @@ -33,9 +33,9 @@ import { Node } from '../scene-graph/node'; import { ICounterOption } from './counter'; import { PerfCounter } from './perf-counter'; import { Pass } from '../render-scene'; -import { preTransforms, System, sys, cclegacy, Settings, settings, warnID } from '../core'; +import { preTransforms, System, sys, cclegacy, settings, warnID, SettingsCategory } from '../core'; import { Root } from '../root'; -import { director } from '../game'; +import { director, DirectorEvent } from '../game'; import { ccwindow } from '../core/global-exports'; const _characters = '0123456789. '; @@ -131,7 +131,7 @@ export class Profiler extends System { } init (): void { - const showFPS = !!settings.querySettings(Settings.Category.PROFILING, 'showFPS'); + const showFPS = !!settings.querySettings(SettingsCategory.PROFILING, 'showFPS'); if (showFPS) { this.showStats(); } else { @@ -165,13 +165,13 @@ export class Profiler extends System { this._rootNode.active = false; } - cclegacy.director.off(cclegacy.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - cclegacy.director.off(cclegacy.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - cclegacy.director.off(cclegacy.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - cclegacy.director.off(cclegacy.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - cclegacy.director.off(cclegacy.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - cclegacy.director.off(cclegacy.Director.EVENT_AFTER_RENDER, this.afterRender, this); - cclegacy.director.off(cclegacy.Director.EVENT_AFTER_DRAW, this.afterPresent, this); + director.off(DirectorEvent.BEFORE_UPDATE, this.beforeUpdate, this); + director.off(DirectorEvent.AFTER_UPDATE, this.afterUpdate, this); + director.off(DirectorEvent.BEFORE_PHYSICS, this.beforePhysics, this); + director.off(DirectorEvent.AFTER_PHYSICS, this.afterPhysics, this); + director.off(DirectorEvent.BEFORE_DRAW, this.beforeDraw, this); + director.off(DirectorEvent.AFTER_RENDER, this.afterRender, this); + director.off(DirectorEvent.AFTER_DRAW, this.afterPresent, this); this._showFPS = false; director.root!.pipeline.profiler = null; cclegacy.game.config.showFPS = false; @@ -195,13 +195,13 @@ export class Profiler extends System { this._rootNode.active = true; } - cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - cclegacy.director.on(cclegacy.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - cclegacy.director.on(cclegacy.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - cclegacy.director.on(cclegacy.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - cclegacy.director.on(cclegacy.Director.EVENT_AFTER_RENDER, this.afterRender, this); - cclegacy.director.on(cclegacy.Director.EVENT_AFTER_DRAW, this.afterPresent, this); + director.on(DirectorEvent.BEFORE_UPDATE, this.beforeUpdate, this); + director.on(DirectorEvent.AFTER_UPDATE, this.afterUpdate, this); + director.on(DirectorEvent.BEFORE_PHYSICS, this.beforePhysics, this); + director.on(DirectorEvent.AFTER_PHYSICS, this.afterPhysics, this); + director.on(DirectorEvent.BEFORE_DRAW, this.beforeDraw, this); + director.on(DirectorEvent.AFTER_RENDER, this.afterRender, this); + director.on(DirectorEvent.AFTER_DRAW, this.afterPresent, this); this._showFPS = true; this._canvasDone = true; diff --git a/cocos/render-scene/core/material-instance.ts b/cocos/render-scene/core/material-instance.ts index e41bb37c753..0fee61db354 100644 --- a/cocos/render-scene/core/material-instance.ts +++ b/cocos/render-scene/core/material-instance.ts @@ -40,25 +40,25 @@ export interface IMaterialInstanceInfo { */ export class MaterialInstance extends Material { get parent (): Material { - return this._parent; + return this._parent$; } get owner (): Renderer | null { - return this._owner; + return this._owner$; } protected _passes: PassInstance[] = []; - private declare _parent: Material; - private declare _owner: Renderer | null; - private _subModelIdx = 0; + private declare _parent$: Material; + private declare _owner$: Renderer | null; + private _subModelIdx$ = 0; constructor (info: IMaterialInstanceInfo) { super(); - this._parent = info.parent; - this._owner = info.owner || null; - this._subModelIdx = info.subModelIdx || 0; - this.copy(this._parent); + this._parent$ = info.parent; + this._owner$ = info.owner || null; + this._subModelIdx$ = info.subModelIdx || 0; + this.copy(this._parent$); } public recompileShaders (overrides: MacroRecord, passIdx?: number): void { @@ -96,14 +96,14 @@ export class MaterialInstance extends Material { public onPassStateChange (dontNotify: boolean): void { this._hash = Material.getHash(this); - if (!dontNotify && this._owner) { - this._owner._onRebuildPSO(this._subModelIdx, this); + if (!dontNotify && this._owner$) { + this._owner$._onRebuildPSO(this._subModelIdx$, this); } } protected _createPasses (): PassInstance[] { const passes: PassInstance[] = []; - const parentPasses = this._parent.passes; + const parentPasses = this._parent$.passes; if (!parentPasses) { return passes; } for (let k = 0; k < parentPasses.length; ++k) { passes.push(new PassInstance(parentPasses[k], this)); diff --git a/cocos/render-scene/core/memory-pools.ts b/cocos/render-scene/core/memory-pools.ts index f166f970bde..45d3c4d6570 100644 --- a/cocos/render-scene/core/memory-pools.ts +++ b/cocos/render-scene/core/memory-pools.ts @@ -65,90 +65,90 @@ class BufferPool

implements IMemor // naming convension: // this._bufferViews[chunk][entry][element] - private declare _dataType: BufferDataTypeManifest; - private declare _dataMembers: BufferDataMembersManifest; - private declare _elementCount: number; - private declare _entryBits: number; - private declare _stride: number; - private declare _entriesPerChunk: number; - private declare _entryMask: number; - private declare _chunkMask: number; - private declare _poolFlag: number; - private _arrayBuffers: ArrayBuffer[] = []; - private _freeLists: number[][] = []; - private _uint32BufferViews: Uint32Array[][] = []; - private _float32BufferViews: Float32Array[][] = []; - private _hasUint32 = false; - private _hasFloat32 = false; - private declare _nativePool: NativeBufferPool; + private declare _dataType$: BufferDataTypeManifest; + private declare _dataMembers$: BufferDataMembersManifest; + private declare _elementCount$: number; + private declare _entryBits$: number; + private declare _stride$: number; + private declare _entriesPerChunk$: number; + private declare _entryMask$: number; + private declare _chunkMask$: number; + private declare _poolFlag$: number; + private _arrayBuffers$: ArrayBuffer[] = []; + private _freeLists$: number[][] = []; + private _uint32BufferViews$: Uint32Array[][] = []; + private _float32BufferViews$: Float32Array[][] = []; + private _hasUint32$ = false; + private _hasFloat32$ = false; + private declare _nativePool$: NativeBufferPool; constructor (poolType: P, dataType: BufferDataTypeManifest, dataMembers: BufferDataMembersManifest, enumType: E, entryBits = 8) { - this._elementCount = enumType.COUNT; - this._entryBits = entryBits; - this._dataType = dataType; - this._dataMembers = dataMembers; + this._elementCount$ = enumType.COUNT; + this._entryBits$ = entryBits; + this._dataType$ = dataType; + this._dataMembers$ = dataMembers; const bytesPerElement = 4; - this._stride = bytesPerElement * this._elementCount; - this._entriesPerChunk = 1 << entryBits; - this._entryMask = this._entriesPerChunk - 1; - this._poolFlag = 1 << 30; - this._chunkMask = ~(this._entryMask | this._poolFlag); - this._nativePool = new NativeBufferPool(poolType, entryBits, this._stride); + this._stride$ = bytesPerElement * this._elementCount$; + this._entriesPerChunk$ = 1 << entryBits; + this._entryMask$ = this._entriesPerChunk$ - 1; + this._poolFlag$ = 1 << 30; + this._chunkMask$ = ~(this._entryMask$ | this._poolFlag$); + this._nativePool$ = new NativeBufferPool(poolType, entryBits, this._stride$); let type: BufferDataType = BufferDataType.NEVER; let hasFloat32 = false; let hasUint32 = false; for (const e in dataType) { - hasFloat32 = this._hasFloat32; - hasUint32 = this._hasUint32; + hasFloat32 = this._hasFloat32$; + hasUint32 = this._hasUint32$; if (hasUint32 && hasFloat32) { break; } type = dataType[e as E[keyof E]]; if (!hasFloat32 && type === BufferDataType.FLOAT32) { - this._hasFloat32 = true; + this._hasFloat32$ = true; } else if (!hasUint32 && type === BufferDataType.UINT32) { - this._hasUint32 = true; + this._hasUint32$ = true; } } } public alloc (): IHandle

{ let i = 0; - for (; i < this._freeLists.length; i++) { - const list = this._freeLists[i]; + for (; i < this._freeLists$.length; i++) { + const list = this._freeLists$[i]; if (list.length) { const j = list[list.length - 1]; list.length--; - return (i << this._entryBits) + j + this._poolFlag as unknown as IHandle

; + return (i << this._entryBits$) + j + this._poolFlag$ as unknown as IHandle

; } } // add a new chunk - const buffer = this._nativePool.allocateNewChunk(); + const buffer = this._nativePool$.allocateNewChunk(); const float32BufferViews: Float32Array[] = []; const uint32BufferViews: Uint32Array[] = []; const freeList: number[] = []; - const hasFloat32 = this._hasFloat32; - const hasUint32 = this._hasUint32; - for (let j = 0; j < this._entriesPerChunk; j++) { - if (hasFloat32) { float32BufferViews.push(new Float32Array(buffer, this._stride * j, this._elementCount)); } - if (hasUint32) { uint32BufferViews.push(new Uint32Array(buffer, this._stride * j, this._elementCount)); } + const hasFloat32 = this._hasFloat32$; + const hasUint32 = this._hasUint32$; + for (let j = 0; j < this._entriesPerChunk$; j++) { + if (hasFloat32) { float32BufferViews.push(new Float32Array(buffer, this._stride$ * j, this._elementCount$)); } + if (hasUint32) { uint32BufferViews.push(new Uint32Array(buffer, this._stride$ * j, this._elementCount$)); } if (j) { freeList.push(j); } } - if (hasUint32) { this._uint32BufferViews.push(uint32BufferViews); } - if (hasFloat32) { this._float32BufferViews.push(float32BufferViews); } - this._freeLists.push(freeList); - this._arrayBuffers.push(buffer); - const handle = (i << this._entryBits) + this._poolFlag as unknown as IHandle

; + if (hasUint32) { this._uint32BufferViews$.push(uint32BufferViews); } + if (hasFloat32) { this._float32BufferViews$.push(float32BufferViews); } + this._freeLists$.push(freeList); + this._arrayBuffers$.push(buffer); + const handle = (i << this._entryBits$) + this._poolFlag$ as unknown as IHandle

; return handle; // guarantees the handle is always not zero } public getBuffer (handle: IHandle

): BufferArrayType { - const chunk = (this._chunkMask & handle as unknown as number) >> this._entryBits; - const entry = this._entryMask & handle as unknown as number; - const bufferViews = this._hasFloat32 ? this._float32BufferViews : this._uint32BufferViews; + const chunk = (this._chunkMask$ & handle as unknown as number) >> this._entryBits$; + const entry = this._entryMask$ & handle as unknown as number; + const bufferViews = this._hasFloat32$ ? this._float32BufferViews$ : this._uint32BufferViews$; if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length - || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) { + || entry < 0 || entry >= this._entriesPerChunk$ || contains(this._freeLists$[chunk], entry))) { warn('invalid buffer pool handle'); return [] as unknown as BufferArrayType; } @@ -157,32 +157,32 @@ class BufferPool

implements IMemor } public getTypedArray (handle: IHandle

, element: K): BufferArrayType { - const chunk = (this._chunkMask & handle as unknown as number) >> this._entryBits; - const entry = this._entryMask & handle as unknown as number; - const bufferViews = this._dataType[element] === BufferDataType.UINT32 ? this._uint32BufferViews : this._float32BufferViews; + const chunk = (this._chunkMask$ & handle as unknown as number) >> this._entryBits$; + const entry = this._entryMask$ & handle as unknown as number; + const bufferViews = this._dataType$[element] === BufferDataType.UINT32 ? this._uint32BufferViews$ : this._float32BufferViews$; if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length - || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) { + || entry < 0 || entry >= this._entriesPerChunk$ || contains(this._freeLists$[chunk], entry))) { warn('invalid buffer pool handle'); return [] as unknown as BufferArrayType; } const index = element as unknown as number; const view = bufferViews[chunk][entry]; - const count = this._dataMembers[element]; + const count = this._dataMembers$[element]; return view.subarray(index, index + count); } public free (handle: IHandle

): void { - const chunk = (this._chunkMask & handle as unknown as number) >> this._entryBits; - const entry = this._entryMask & handle as unknown as number; - if (DEBUG && (!handle || chunk < 0 || chunk >= this._freeLists.length - || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) { + const chunk = (this._chunkMask$ & handle as unknown as number) >> this._entryBits$; + const entry = this._entryMask$ & handle as unknown as number; + if (DEBUG && (!handle || chunk < 0 || chunk >= this._freeLists$.length + || entry < 0 || entry >= this._entriesPerChunk$ || contains(this._freeLists$[chunk], entry))) { warn('invalid buffer pool handle'); return; } - const bufferViews = this._hasUint32 ? this._uint32BufferViews : this._float32BufferViews; + const bufferViews = this._hasUint32$ ? this._uint32BufferViews$ : this._float32BufferViews$; bufferViews[chunk][entry].fill(0); - this._freeLists[chunk].push(entry); + this._freeLists$[chunk].push(entry); } } diff --git a/cocos/render-scene/core/native-pools.ts b/cocos/render-scene/core/native-pools.ts index c225de9109e..42fbd68417d 100644 --- a/cocos/render-scene/core/native-pools.ts +++ b/cocos/render-scene/core/native-pools.ts @@ -23,12 +23,12 @@ */ export class NativeBufferPool { - private _arrayBuffers: ArrayBuffer[] = []; - private declare _chunkSize: number; + private _arrayBuffers$: ArrayBuffer[] = []; + private declare _chunkSize$: number; constructor (dataType: number, entryBits: number, stride: number) { - this._chunkSize = stride * (1 << entryBits); + this._chunkSize$ = stride * (1 << entryBits); } - public allocateNewChunk (): ArrayBuffer { return new ArrayBuffer(this._chunkSize); } + public allocateNewChunk (): ArrayBuffer { return new ArrayBuffer(this._chunkSize$); } } export class NativeObjectPool { diff --git a/cocos/render-scene/core/pass-instance.ts b/cocos/render-scene/core/pass-instance.ts index 0a5718fd5e4..110c0f90dc8 100644 --- a/cocos/render-scene/core/pass-instance.ts +++ b/cocos/render-scene/core/pass-instance.ts @@ -36,27 +36,27 @@ export class PassInstance extends Pass { * @en The parent pass * @zh 相关联的原始 Pass */ - get parent (): Pass { return this._parent; } + get parent (): Pass { return this._parent$; } - private declare _parent: Pass; + private declare _parent$: Pass; - private declare _owner: MaterialInstance; + private declare _owner$: MaterialInstance; - private _dontNotify = false; + private _dontNotify$ = false; constructor (parent: Pass, owner: MaterialInstance) { super(parent.root); - this._parent = parent; - this._owner = owner; - this._doInit(this._parent, true); // defines may change now + this._parent$ = parent; + this._owner$ = owner; + this._doInit(this._parent$, true); // defines may change now for (let i = 0; i < this._shaderInfo.blocks.length; i++) { const u = this._shaderInfo.blocks[i]; const block = this._blocks[u.binding]; - const parentBlock = this._parent.blocks[u.binding]; + const parentBlock = this._parent$.blocks[u.binding]; block.set(parentBlock); } this._rootBufferDirty = true; - const paren = this._parent as PassInstance; + const paren = this._parent$ as PassInstance; for (let i = 0; i < this._shaderInfo.samplerTextures.length; i++) { const u = this._shaderInfo.samplerTextures[i]; for (let j = 0; j < u.count; j++) { @@ -102,7 +102,7 @@ export class PassInstance extends Pass { * @zh 开始静默修改 Pass 相关状态,不会通知材质去重新构建管线状态对象。 */ public beginChangeStatesSilently (): void { - this._dontNotify = true; + this._dontNotify$ = true; } /** @@ -110,7 +110,7 @@ export class PassInstance extends Pass { * @zh 结束静默状态修改,所有修改将会开始通知材质。 */ public endChangeStatesSilently (): void { - this._dontNotify = false; + this._dontNotify$ = false; } protected _syncBatchingScheme (): void { @@ -120,6 +120,6 @@ export class PassInstance extends Pass { protected _onStateChange (): void { this._hash = Pass.getPassHash(this); - this._owner.onPassStateChange(this._dontNotify); + this._owner$.onPassStateChange(this._dontNotify$); } } diff --git a/cocos/render-scene/core/pass.ts b/cocos/render-scene/core/pass.ts index 00d808c6a25..bfdf5500b46 100644 --- a/cocos/render-scene/core/pass.ts +++ b/cocos/render-scene/core/pass.ts @@ -269,7 +269,7 @@ export class Pass { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); - const block = this._getBlockView(type, binding); + const block = this._getBlockView$(type, binding); if (DEBUG) { const validator = type2validator[type]; assertID(Boolean(validator && validator(value)), 12011, binding, Type[type]); @@ -288,7 +288,7 @@ export class Pass { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); - const block = this._getBlockView(type, binding); + const block = this._getBlockView$(type, binding); return type2reader[type](block, out, ofs) as T; } @@ -302,7 +302,7 @@ export class Pass { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const stride = GetTypeSize(type) >> 2; - const block = this._getBlockView(type, binding); + const block = this._getBlockView$(type, binding); let ofs = Pass.getOffsetFromHandle(handle); for (let i = 0; i < value.length; i++, ofs += stride) { if (value[i] === null) { continue; } @@ -412,7 +412,7 @@ export class Pass { const binding = Pass.getBindingFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); const count = Pass.getCountFromHandle(handle); - const block = this._getBlockView(type, binding); + const block = this._getBlockView$(type, binding); const info = this._properties[name]; const givenDefault = info && info.value; const value = (givenDefault || getDefaultFromType(type)) as number[]; @@ -456,7 +456,7 @@ export class Pass { let ofs = 0; for (let j = 0; j < u.members.length; j++) { const cur = u.members[j]; - const block = this._getBlockView(cur.type, u.binding); + const block = this._getBlockView$(cur.type, u.binding); const info = this._properties[cur.name]; const givenDefault = info && info.value; const value = (givenDefault || getDefaultFromType(cur.type)) as number[]; @@ -680,9 +680,9 @@ export class Pass { if (cclegacy.rendering && cclegacy.rendering.enableEffectImport) { const programLib = (cclegacy.rendering.programLib as ProgramLibrary); const shaderInfo = programLib.getShaderInfo(this._phaseID, this.program); - this._buildMaterialUniformBlocks(device, shaderInfo.blocks, blockSizes); + this._buildMaterialUniformBlocks$(device, shaderInfo.blocks, blockSizes); } else { - this._buildUniformBlocks(device, blocks, blockSizes); + this._buildUniformBlocks$(device, blocks, blockSizes); } // store handles @@ -696,7 +696,7 @@ export class Pass { Object.assign(directHandleMap, indirectHandleMap); } - private _buildUniformBlocks (device: Device, blocks: EffectAsset.IBlockInfo[], blockSizes: number[]): void { + private _buildUniformBlocks$ (device: Device, blocks: EffectAsset.IBlockInfo[], blockSizes: number[]): void { const alignment = device.capabilities.uboOffsetAlignment; const startOffsets: number[] = []; let lastSize = 0; let lastOffset = 0; @@ -734,7 +734,7 @@ export class Pass { } } - private _buildMaterialUniformBlocks (device: Device, blocks: UniformBlock[], blockSizes: number[]): void { + private _buildMaterialUniformBlocks$ (device: Device, blocks: UniformBlock[], blockSizes: number[]): void { const alignment = device.capabilities.uboOffsetAlignment; const startOffsets: number[] = []; let lastSize = 0; let lastOffset = 0; @@ -795,7 +795,7 @@ export class Pass { } } - private _getBlockView (type: Type, binding: number): Int32Array | Float32Array { + private _getBlockView$ (type: Type, binding: number): Int32Array | Float32Array { return type < Type.FLOAT ? this._blocksInt[binding] : this._blocks[binding]; } diff --git a/cocos/render-scene/core/program-utils.ts b/cocos/render-scene/core/program-utils.ts index bc77bde5b6c..68d6a563013 100644 --- a/cocos/render-scene/core/program-utils.ts +++ b/cocos/render-scene/core/program-utils.ts @@ -25,7 +25,7 @@ import { EffectAsset } from '../../asset/assets/effect-asset'; import { errorID, warnID } from '../../core/platform/debug'; import { Attribute, GetTypeSize, ShaderInfo, Uniform } from '../../gfx/base/define'; -import { UBOForwardLight, UBOSkinning } from '../../rendering/define'; +import { UBOForwardLight, UBOForwardLightEnum, UBOSkinning } from '../../rendering/define'; import { genHandle, MacroRecord } from './pass-utils'; import { IProgramInfo } from './program-lib'; @@ -117,11 +117,11 @@ export function getVariantKey (programInfo: IProgramInfo, defines: MacroRecord): const defaultUniformCounts = new Map(); defaultUniformCounts.set('cc_joints', UBOSkinning.LAYOUT.members[0].count); -defaultUniformCounts.set('cc_lightPos', UBOForwardLight.LIGHTS_PER_PASS); -defaultUniformCounts.set('cc_lightColor', UBOForwardLight.LIGHTS_PER_PASS); -defaultUniformCounts.set('cc_lightSizeRangeAngle', UBOForwardLight.LIGHTS_PER_PASS); -defaultUniformCounts.set('cc_lightDir', UBOForwardLight.LIGHTS_PER_PASS); -defaultUniformCounts.set('cc_lightBoundingSizeVS', UBOForwardLight.LIGHTS_PER_PASS); +defaultUniformCounts.set('cc_lightPos', UBOForwardLightEnum.LIGHTS_PER_PASS); +defaultUniformCounts.set('cc_lightColor', UBOForwardLightEnum.LIGHTS_PER_PASS); +defaultUniformCounts.set('cc_lightSizeRangeAngle', UBOForwardLightEnum.LIGHTS_PER_PASS); +defaultUniformCounts.set('cc_lightDir', UBOForwardLightEnum.LIGHTS_PER_PASS); +defaultUniformCounts.set('cc_lightBoundingSizeVS', UBOForwardLightEnum.LIGHTS_PER_PASS); function getUniformSize (prevSize: number, m: Uniform): number { if (m.count) { diff --git a/cocos/render-scene/core/render-scene.ts b/cocos/render-scene/core/render-scene.ts index c0acfbe3ab6..642994c8b85 100644 --- a/cocos/render-scene/core/render-scene.ts +++ b/cocos/render-scene/core/render-scene.ts @@ -70,7 +70,7 @@ export class RenderScene { * @zh 基础渲染管理器。 */ get root (): Root { - return this._root; + return this._root$; } /** @@ -78,7 +78,7 @@ export class RenderScene { * @zh 渲染场景的名称。 */ get name (): string { - return this._name; + return this._name$; } /** @@ -86,7 +86,7 @@ export class RenderScene { * @zh 渲染场景管理的所有相机。 */ get cameras (): Camera[] { - return this._cameras; + return this._cameras$; } /** @@ -94,7 +94,7 @@ export class RenderScene { * @zh 渲染场景管理的主方向光源。 */ get mainLight (): DirectionalLight | null { - return this._mainLight; + return this._mainLight$; } /** @@ -102,7 +102,7 @@ export class RenderScene { * @zh 渲染场景管理的所有球面光源。 */ get sphereLights (): Readonly { - return this._sphereLights; + return this._sphereLights$; } /** @@ -110,7 +110,7 @@ export class RenderScene { * @zh 渲染场景管理的所有聚光灯光源。 */ get spotLights (): Readonly { - return this._spotLights; + return this._spotLights$; } /** @@ -118,7 +118,7 @@ export class RenderScene { * @zh 渲染场景管理的所有点光源。 */ get pointLights (): Readonly { - return this._pointLights; + return this._pointLights$; } /** @@ -126,7 +126,7 @@ export class RenderScene { * @zh 渲染场景管理的所有范围平行光光源。 */ get rangedDirLights (): Readonly { - return this._rangedDirLights; + return this._rangedDirLights$; } /** @@ -134,7 +134,7 @@ export class RenderScene { * @zh 渲染场景管理的所有模型。 */ get models (): Model[] { - return this._models; + return this._models$; } /** @@ -142,7 +142,7 @@ export class RenderScene { * @zh 渲染场景管理的所有 2D 渲染批次对象。 */ get batches (): DrawBatch2D[] { - return this._batches; + return this._batches$; } /** @@ -150,22 +150,22 @@ export class RenderScene { * @en All LOD groups of the render scene. * @zh 渲染场景管理的所有 LOD 组。 */ - get lodGroups (): readonly LODGroup[] { return this._lodGroups; } + get lodGroups (): readonly LODGroup[] { return this._lodGroups$; } - private declare _root: Root; - private _name = ''; - private _cameras: Camera[] = []; - private _models: Model[] = []; - private _lodGroups: LODGroup[] = []; // LOD Group gathered - private _batches: DrawBatch2D[] = []; - private _directionalLights: DirectionalLight[] = []; - private _sphereLights: SphereLight[] = []; - private _spotLights: SpotLight[] = []; - private _pointLights: PointLight[] = []; - private _rangedDirLights: RangedDirectionalLight[] = []; - private _mainLight: DirectionalLight | null = null; - private _modelId = 0; - private _lodStateCache: LodStateCache = null!; + private declare _root$: Root; + private _name$ = ''; + private _cameras$: Camera[] = []; + private _models$: Model[] = []; + private _lodGroups$: LODGroup[] = []; // LOD Group gathered + private _batches$: DrawBatch2D[] = []; + private _directionalLights$: DirectionalLight[] = []; + private _sphereLights$: SphereLight[] = []; + private _spotLights$: SpotLight[] = []; + private _pointLights$: PointLight[] = []; + private _rangedDirLights$: RangedDirectionalLight[] = []; + private _mainLight$: DirectionalLight | null = null; + private _modelId$ = 0; + private _lodStateCache$: LodStateCache = null!; /** * Register the creation function of the render scene to root. @@ -176,7 +176,7 @@ export class RenderScene { } constructor (root: Root) { - this._root = root; + this._root$ = root; } /** @@ -185,8 +185,8 @@ export class RenderScene { * @returns Successful */ public initialize (info: IRenderSceneInfo): boolean { - this._name = info.name; - this._lodStateCache = new LodStateCache(this); + this._name$ = info.name; + this._lodStateCache$ = new LodStateCache(this); return true; } @@ -197,36 +197,36 @@ export class RenderScene { * @returns void */ public update (stamp: number): void { - const mainLight = this._mainLight; + const mainLight = this._mainLight$; if (mainLight) { mainLight.update(); } - const sphereLights = this._sphereLights; + const sphereLights = this._sphereLights$; for (let i = 0; i < sphereLights.length; i++) { const light = sphereLights[i]; light.update(); } - const spotLights = this._spotLights; + const spotLights = this._spotLights$; for (let i = 0; i < spotLights.length; i++) { const light = spotLights[i]; light.update(); } - const pointLights = this._pointLights; + const pointLights = this._pointLights$; for (let i = 0; i < pointLights.length; i++) { const light = pointLights[i]; light.update(); } - const rangedDirLights = this._rangedDirLights; + const rangedDirLights = this._rangedDirLights$; for (let i = 0; i < rangedDirLights.length; i++) { const light = rangedDirLights[i]; light.update(); } - const models = this._models; + const models = this._models$; for (let i = 0; i < models.length; i++) { const model = models[i]; @@ -235,7 +235,7 @@ export class RenderScene { model.updateUBOs(stamp); } } - this._lodStateCache.updateLodState(); + this._lodStateCache$.updateLodState(); } /** @@ -249,11 +249,11 @@ export class RenderScene { this.removeRangedDirLights(); this.removeModels(); this.removeLODGroups(); - this._lodStateCache.clearCache(); + this._lodStateCache$.clearCache(); } public isCulledByLod (camera: Camera, model: Model): boolean { - return this._lodStateCache.isLodModelCulled(camera, model); + return this._lodStateCache$.isLodModelCulled(camera, model); } /** @@ -262,8 +262,8 @@ export class RenderScene { */ public addCamera (cam: Camera): void { cam.attachToScene(this); - this._cameras.push(cam); - this._lodStateCache.addCamera(cam); + this._cameras$.push(cam); + this._lodStateCache$.addCamera(cam); } /** @@ -271,11 +271,11 @@ export class RenderScene { * @zh 从渲染场景移除一个相机 */ public removeCamera (camera: Camera): void { - for (let i = 0; i < this._cameras.length; ++i) { - if (this._cameras[i] === camera) { - this._cameras.splice(i, 1); + for (let i = 0; i < this._cameras$.length; ++i) { + if (this._cameras$[i] === camera) { + this._cameras$.splice(i, 1); camera.detachFromScene(); - this._lodStateCache.removeCamera(camera); + this._lodStateCache$.removeCamera(camera); return; } } @@ -286,11 +286,11 @@ export class RenderScene { * @zh 从渲染场景移除所有相机 */ public removeCameras (): void { - for (const camera of this._cameras) { + for (const camera of this._cameras$) { camera.detachFromScene(); - this._lodStateCache.removeCamera(camera); + this._lodStateCache$.removeCamera(camera); } - this._cameras.splice(0); + this._cameras$.splice(0); } /** @@ -299,8 +299,8 @@ export class RenderScene { * @param dl The main directional light source */ public setMainLight (dl: DirectionalLight | null): void { - this._mainLight = dl; - if (this._mainLight) this._mainLight.activate(); + this._mainLight$ = dl; + if (this._mainLight$) this._mainLight$.activate(); } /** @@ -309,12 +309,12 @@ export class RenderScene { * @param dl The main directional light source, if it's not the actual main light, nothing happens. */ public unsetMainLight (dl: DirectionalLight): void { - if (this._mainLight === dl) { - const dlList = this._directionalLights; + if (this._mainLight$ === dl) { + const dlList = this._directionalLights$; if (dlList.length) { this.setMainLight(dlList[dlList.length - 1]); - if (this._mainLight.node) { // trigger update - this._mainLight.node.hasChangedFlags |= TransformBit.ROTATION; + if (this._mainLight$.node) { // trigger update + this._mainLight$.node.hasChangedFlags |= TransformBit.ROTATION; } return; } @@ -329,7 +329,7 @@ export class RenderScene { */ public addDirectionalLight (dl: DirectionalLight): void { dl.attachToScene(this); - this._directionalLights.push(dl); + this._directionalLights$.push(dl); } /** @@ -338,10 +338,10 @@ export class RenderScene { * @param dl The directional light. */ public removeDirectionalLight (dl: DirectionalLight): void { - for (let i = 0; i < this._directionalLights.length; ++i) { - if (this._directionalLights[i] === dl) { + for (let i = 0; i < this._directionalLights$.length; ++i) { + if (this._directionalLights$[i] === dl) { dl.detachFromScene(); - this._directionalLights.splice(i, 1); + this._directionalLights$.splice(i, 1); return; } } @@ -354,7 +354,7 @@ export class RenderScene { */ public addSphereLight (pl: SphereLight): void { pl.attachToScene(this); - this._sphereLights.push(pl); + this._sphereLights$.push(pl); } /** @@ -363,10 +363,10 @@ export class RenderScene { * @param pl The sphere light. */ public removeSphereLight (pl: SphereLight): void { - for (let i = 0; i < this._sphereLights.length; ++i) { - if (this._sphereLights[i] === pl) { + for (let i = 0; i < this._sphereLights$.length; ++i) { + if (this._sphereLights$[i] === pl) { pl.detachFromScene(); - this._sphereLights.splice(i, 1); + this._sphereLights$.splice(i, 1); return; } @@ -380,7 +380,7 @@ export class RenderScene { */ public addSpotLight (sl: SpotLight): void { sl.attachToScene(this); - this._spotLights.push(sl); + this._spotLights$.push(sl); } /** @@ -389,10 +389,10 @@ export class RenderScene { * @param sl The spot light. */ public removeSpotLight (sl: SpotLight): void { - for (let i = 0; i < this._spotLights.length; ++i) { - if (this._spotLights[i] === sl) { + for (let i = 0; i < this._spotLights$.length; ++i) { + if (this._spotLights$[i] === sl) { sl.detachFromScene(); - this._spotLights.splice(i, 1); + this._spotLights$.splice(i, 1); return; } @@ -404,10 +404,10 @@ export class RenderScene { * @zh 删除所有球面光源。 */ public removeSphereLights (): void { - for (let i = 0; i < this._sphereLights.length; ++i) { - this._sphereLights[i].detachFromScene(); + for (let i = 0; i < this._sphereLights$.length; ++i) { + this._sphereLights$[i].detachFromScene(); } - this._sphereLights.length = 0; + this._sphereLights$.length = 0; } /** @@ -415,10 +415,10 @@ export class RenderScene { * @zh 删除所有聚光灯光源。 */ public removeSpotLights (): void { - for (let i = 0; i < this._spotLights.length; ++i) { - this._spotLights[i].detachFromScene(); + for (let i = 0; i < this._spotLights$.length; ++i) { + this._spotLights$[i].detachFromScene(); } - this._spotLights.length = 0; + this._spotLights$.length = 0; } /** @@ -428,7 +428,7 @@ export class RenderScene { */ public addPointLight (pl: PointLight): void { pl.attachToScene(this); - this._pointLights.push(pl); + this._pointLights$.push(pl); } /** @@ -437,10 +437,10 @@ export class RenderScene { * @param pl @en The point light. @zh 点光源。 */ public removePointLight (pl: PointLight): void { - for (let i = 0; i < this._pointLights.length; ++i) { - if (this._pointLights[i] === pl) { + for (let i = 0; i < this._pointLights$.length; ++i) { + if (this._pointLights$[i] === pl) { pl.detachFromScene(); - this._pointLights.splice(i, 1); + this._pointLights$.splice(i, 1); return; } } @@ -451,10 +451,10 @@ export class RenderScene { * @zh 删除所有点光源。 */ public removePointLights (): void { - for (let i = 0; i < this._pointLights.length; ++i) { - this._pointLights[i].detachFromScene(); + for (let i = 0; i < this._pointLights$.length; ++i) { + this._pointLights$[i].detachFromScene(); } - this._pointLights.length = 0; + this._pointLights$.length = 0; } /** @@ -464,7 +464,7 @@ export class RenderScene { */ public addRangedDirLight (l: RangedDirectionalLight): void { l.attachToScene(this); - this._rangedDirLights.push(l); + this._rangedDirLights$.push(l); } /** @@ -473,10 +473,10 @@ export class RenderScene { * @param l @en The ranged directional light. @zh 范围平行光。 */ public removeRangedDirLight (l: RangedDirectionalLight): void { - for (let i = 0; i < this._rangedDirLights.length; ++i) { - if (this._rangedDirLights[i] === l) { + for (let i = 0; i < this._rangedDirLights$.length; ++i) { + if (this._rangedDirLights$[i] === l) { l.detachFromScene(); - this._rangedDirLights.splice(i, 1); + this._rangedDirLights$.splice(i, 1); return; } } @@ -487,10 +487,10 @@ export class RenderScene { * @zh 删除所有范围平行光源。 */ public removeRangedDirLights (): void { - for (let i = 0; i < this._rangedDirLights.length; ++i) { - this._rangedDirLights[i].detachFromScene(); + for (let i = 0; i < this._rangedDirLights$.length; ++i) { + this._rangedDirLights$[i].detachFromScene(); } - this._rangedDirLights.length = 0; + this._rangedDirLights$.length = 0; } /** @@ -500,7 +500,7 @@ export class RenderScene { */ public addModel (m: Model): void { m.attachToScene(this); - this._models.push(m); + this._models$.push(m); } /** @@ -509,11 +509,11 @@ export class RenderScene { * @param m The model. */ public removeModel (model: Model): void { - for (let i = 0; i < this._models.length; ++i) { - if (this._models[i] === model) { - this._lodStateCache.removeModel(model); + for (let i = 0; i < this._models$.length; ++i) { + if (this._models$[i] === model) { + this._lodStateCache$.removeModel(model); model.detachFromScene(); - this._models.splice(i, 1); + this._models$.splice(i, 1); return; } @@ -525,12 +525,12 @@ export class RenderScene { * @zh 删除所有模型。 */ public removeModels (): void { - for (const m of this._models) { - this._lodStateCache.removeModel(m); + for (const m of this._models$) { + this._lodStateCache$.removeModel(m); m.detachFromScene(); m.destroy(); } - this._models.length = 0; + this._models$.length = 0; } /** @@ -541,7 +541,7 @@ export class RenderScene { * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ public addBatch (batch: DrawBatch2D): void { - this._batches.push(batch); + this._batches$.push(batch); } /** @@ -552,9 +552,9 @@ export class RenderScene { * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ public removeBatch (batch: DrawBatch2D): void { - for (let i = 0; i < this._batches.length; ++i) { - if (this._batches[i] === batch) { - this._batches.splice(i, 1); + for (let i = 0; i < this._batches$.length; ++i) { + if (this._batches$[i] === batch) { + this._batches$.splice(i, 1); return; } } @@ -567,7 +567,7 @@ export class RenderScene { * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. */ public removeBatches (): void { - this._batches.length = 0; + this._batches$.length = 0; } /** @@ -577,9 +577,9 @@ export class RenderScene { * @param lodGroup the LOD group */ addLODGroup (lodGroup: LODGroup): void { - this._lodGroups.push(lodGroup); + this._lodGroups$.push(lodGroup); lodGroup.attachToScene(this); - this._lodStateCache.addLodGroup(lodGroup); + this._lodStateCache$.addLodGroup(lodGroup); } /** @@ -589,11 +589,11 @@ export class RenderScene { * @param lodGroup the LOD group */ removeLODGroup (lodGroup: LODGroup): void { - const index = this._lodGroups.indexOf(lodGroup); + const index = this._lodGroups$.indexOf(lodGroup); if (index >= 0) { - this._lodGroups.splice(index, 1); + this._lodGroups$.splice(index, 1); lodGroup.detachFromScene(); - this._lodStateCache.removeLodGroup(lodGroup); + this._lodStateCache$.removeLodGroup(lodGroup); } } @@ -603,10 +603,10 @@ export class RenderScene { * @zh 删除所有LOD 组。 */ removeLODGroups (): void { - for (const group of this._lodGroups) { - this._lodStateCache.removeLodGroup(group); + for (const group of this._lodGroups$) { + this._lodStateCache$.removeLodGroup(group); } - this._lodGroups.length = 0; + this._lodGroups$.length = 0; } /** @@ -614,7 +614,7 @@ export class RenderScene { * @zh 通知所有模型全局管线状态已更新,需要更新自身状态。 */ public onGlobalPipelineStateChanged (): void { - for (const m of this._models) { + for (const m of this._models$) { m.onGlobalPipelineStateChanged(); } } @@ -625,7 +625,7 @@ export class RenderScene { * @returns The model id */ public generateModelId (): number { - return this._modelId++; + return this._modelId$++; } } @@ -646,16 +646,16 @@ class LODInfo { */ class LodStateCache { constructor (scene: RenderScene) { - this._renderScene = scene; + this._renderScene$ = scene; } addCamera (camera: Camera): void { const needRegisterChanged = false; - for (const lodGroup of this._renderScene.lodGroups) { + for (const lodGroup of this._renderScene$.lodGroups) { const layer = lodGroup.node.layer; if ((camera.visibility & layer) === layer) { - if (!this._lodStateInCamera.has(camera)) { - this._lodStateInCamera.set(camera, new Map()); + if (!this._lodStateInCamera$.has(camera)) { + this._lodStateInCamera$.set(camera, new Map()); } break; } @@ -663,21 +663,21 @@ class LodStateCache { } removeCamera (camera: Camera): void { - if (this._lodStateInCamera.has(camera)) { - this._lodStateInCamera.delete(camera); + if (this._lodStateInCamera$.has(camera)) { + this._lodStateInCamera$.delete(camera); } } addLodGroup (lodGroup: LODGroup): void { - this._newAddedLodGroupVec.push(lodGroup); + this._newAddedLodGroupVec$.push(lodGroup); - for (const camera of this._renderScene.cameras) { - if (this._lodStateInCamera.has(camera)) { + for (const camera of this._renderScene$.cameras) { + if (this._lodStateInCamera$.has(camera)) { continue; } const layer = lodGroup.node.layer; if ((camera.visibility & layer) === layer) { - this._lodStateInCamera.set(camera, new Map()); + this._lodStateInCamera$.set(camera, new Map()); } } } @@ -686,29 +686,29 @@ class LodStateCache { for (let index = 0; index < lodGroup.lodCount; index++) { const lod = lodGroup.lodDataArray[index]; for (const model of lod.models) { - this._modelsInLODGroup.delete(model); + this._modelsInLODGroup$.delete(model); } } - for (const visibleCamera of this._lodStateInCamera) { + for (const visibleCamera of this._lodStateInCamera$) { visibleCamera[1].delete(lodGroup); } - this._levelModels.delete(lodGroup); + this._levelModels$.delete(lodGroup); } removeModel (model: Model): void { - if (this._modelsInLODGroup.has(model)) { - this._modelsInLODGroup.delete(model); + if (this._modelsInLODGroup$.has(model)) { + this._modelsInLODGroup$.delete(model); } } // Update list of visible cameras on _modelsInLODGroup and update lod usage level under specified camera. updateLodState (): void { // insert vecAddedLodGroup's model into modelsByAnyLODGroup - for (const addedLodGroup of this._newAddedLodGroupVec) { - let levelModels = this._levelModels.get(addedLodGroup); + for (const addedLodGroup of this._newAddedLodGroupVec$) { + let levelModels = this._levelModels$.get(addedLodGroup); if (!levelModels) { levelModels = new Map>(); - this._levelModels.set(addedLodGroup, levelModels); + this._levelModels$.set(addedLodGroup, levelModels); } for (let index = 0; index < addedLodGroup.lodCount; index++) { let lodModels = levelModels.get(index); @@ -717,20 +717,20 @@ class LodStateCache { } const lod = addedLodGroup.lodDataArray[index]; for (const model of lod.models) { - let modelInfo = this._modelsInLODGroup.get(model); + let modelInfo = this._modelsInLODGroup$.get(model); if (!modelInfo) { modelInfo = new Map(); } - this._modelsInLODGroup.set(model, modelInfo); + this._modelsInLODGroup$.set(model, modelInfo); lodModels.push(model); } levelModels.set(index, lodModels); } } - this._newAddedLodGroupVec.length = 0; + this._newAddedLodGroupVec$.length = 0; // update current visible lod index & model's visible cameras list - for (const lodGroup of this._renderScene.lodGroups) { + for (const lodGroup of this._renderScene$.lodGroups) { if (lodGroup.enabled) { const lodLevels = lodGroup.getLockedLODLevels(); const count = lodLevels.length; @@ -740,7 +740,7 @@ class LodStateCache { // Update the dirty flag to make it easier to update the visible // index of lod after lifting the forced use of lod. if (lodGroup.node.hasChangedFlags > 0) { - for (const visibleCamera of this._lodStateInCamera) { + for (const visibleCamera of this._lodStateInCamera$) { let lodInfo = visibleCamera[1].get(lodGroup); if (!lodInfo) { lodInfo = new LODInfo(); @@ -754,11 +754,11 @@ class LodStateCache { if (lodGroup.isLockLevelChanged()) { lodGroup.resetLockChangeFlag(); - const lodModels = this._levelModels.get(lodGroup); + const lodModels = this._levelModels$.get(lodGroup); if (lodModels) { lodModels.forEach((vecArray, index): void => { vecArray.forEach((model): void => { - const modelInfo = this._modelsInLODGroup.get(model); + const modelInfo = this._modelsInLODGroup$.get(model); if (modelInfo) { modelInfo.clear(); } @@ -769,9 +769,9 @@ class LodStateCache { const vecModels = lodModels.get(visibleIndex); if (vecModels) { vecModels.forEach((model): void => { - const modelInfo = this._modelsInLODGroup.get(model); + const modelInfo = this._modelsInLODGroup$.get(model); if (modelInfo && model.node && model.node.active) { - for (const visibleCamera of this._lodStateInCamera) { + for (const visibleCamera of this._lodStateInCamera$) { modelInfo.set(visibleCamera[0], true); } } @@ -785,7 +785,7 @@ class LodStateCache { // Normal Process, no LOD is forced. let hasUpdated = false; - for (const visibleCamera of this._lodStateInCamera) { + for (const visibleCamera of this._lodStateInCamera$) { let lodInfo = visibleCamera[1].get(lodGroup); if (!lodInfo) { lodInfo = new LODInfo(); @@ -809,7 +809,7 @@ class LodStateCache { } } - const lodModels = this._levelModels.get(lodGroup); + const lodModels = this._levelModels$.get(lodGroup); if (!lodModels) { continue; } @@ -821,7 +821,7 @@ class LodStateCache { lodModels.forEach((vecArray, index): void => { vecArray.forEach((model): void => { - const modelInfo = this._modelsInLODGroup.get(model); + const modelInfo = this._modelsInLODGroup$.get(model); if (modelInfo) { modelInfo.clear(); } @@ -829,13 +829,13 @@ class LodStateCache { }); hasUpdated = true; } else if (hasUpdated) { - this._lodStateInCamera.forEach((lodState, camera): void => { + this._lodStateInCamera$.forEach((lodState, camera): void => { const lodInfo = lodState.get(lodGroup); if (lodInfo && lodInfo.usedLevel !== lodInfo.lastUsedLevel) { const vecModels = lodModels.get(lodInfo.lastUsedLevel); if (vecModels) { vecModels.forEach((model): void => { - const modelInfo = this._modelsInLODGroup.get(model); + const modelInfo = this._modelsInLODGroup$.get(model); if (modelInfo) { modelInfo.clear(); } @@ -846,14 +846,14 @@ class LodStateCache { } if (hasUpdated) { - this._lodStateInCamera.forEach((lodState, camera): void => { + this._lodStateInCamera$.forEach((lodState, camera): void => { const lodInfo = lodState.get(lodGroup); if (lodInfo) { const usedLevel = lodInfo.usedLevel; const vecModels = lodModels.get(usedLevel); if (vecModels) { vecModels.forEach((model): void => { - const modelInfo = this._modelsInLODGroup.get(model); + const modelInfo = this._modelsInLODGroup$.get(model); if (modelInfo && model.node && model.node.active) { modelInfo.set(camera, true); } @@ -867,7 +867,7 @@ class LodStateCache { } isLodModelCulled (camera: Camera, model: Model): boolean { - const modelInfo = this._modelsInLODGroup.get(model); + const modelInfo = this._modelsInLODGroup$.get(model); if (!modelInfo) { return false; } @@ -876,37 +876,37 @@ class LodStateCache { } clearCache (): void { - this._levelModels.clear(); - this._modelsInLODGroup.clear(); - this._lodStateInCamera.clear(); - this._newAddedLodGroupVec.length = 0; + this._levelModels$.clear(); + this._modelsInLODGroup$.clear(); + this._lodStateInCamera$.clear(); + this._newAddedLodGroupVec$.length = 0; } - private isLodGroupVisibleByCamera (lodGroup: LODGroup, camera: Camera): boolean { + private isLodGroupVisibleByCamera$ (lodGroup: LODGroup, camera: Camera): boolean { const layer = lodGroup.node.layer; return (camera.visibility & layer) === layer; } - private _renderScene: RenderScene = null!; + private _renderScene$: RenderScene = null!; /** * @zh LOD使用的model集合以及每个model当前能被看到的相机列表;包含每个LODGroup的每一级LOD * @en The set of models used by the LOD and the list of cameras that each models can currently be seen, * contains each level of LOD for each LODGroup. */ - private _modelsInLODGroup: Map> = new Map>(); + private _modelsInLODGroup$: Map> = new Map>(); /** * @zh 指定相机下,LODGroup使用哪一级的LOD * @en Specify which level of LOD is used by the LODGroup under the camera. */ - private _lodStateInCamera: Map> = new Map>(); + private _lodStateInCamera$: Map> = new Map>(); /** * @zh 上一帧添加的lodgroup * @en The lodgroup added in the previous frame. */ - private _newAddedLodGroupVec: Array = new Array(); + private _newAddedLodGroupVec$: Array = new Array(); - private _levelModels: Map>> = new Map>>(); + private _levelModels$: Map>> = new Map>>(); } diff --git a/cocos/render-scene/core/texture-buffer-pool.ts b/cocos/render-scene/core/texture-buffer-pool.ts index 7c10978de84..8c0f89983f6 100644 --- a/cocos/render-scene/core/texture-buffer-pool.ts +++ b/cocos/render-scene/core/texture-buffer-pool.ts @@ -63,64 +63,64 @@ function roundUp (n: number, alignment: number): number { } export class TextureBufferPool { - private declare _device: Device; - private _format = Format.UNKNOWN; - private _formatSize = 0; - private _chunks: ITextureBuffer[] = []; - private _chunkCount = 0; - private _handles: ITextureBufferHandle[] = []; - private _region0 = new BufferTextureCopy(); - private _region1 = new BufferTextureCopy(); - private _region2 = new BufferTextureCopy(); - private _roundUpFn: ((targetSize: number, formatSize: number) => number) | null = null; - private _bufferViewCtor: TypedArrayConstructor = Uint8Array; - private _channels = 4; - private _alignment = 1; + private declare _device$: Device; + private _format$ = Format.UNKNOWN; + private _formatSize$ = 0; + private _chunks$: ITextureBuffer[] = []; + private _chunkCount$ = 0; + private _handles$: ITextureBufferHandle[] = []; + private _region0$ = new BufferTextureCopy(); + private _region1$ = new BufferTextureCopy(); + private _region2$ = new BufferTextureCopy(); + private _roundUpFn$: ((targetSize: number, formatSize: number) => number) | null = null; + private _bufferViewCtor$: TypedArrayConstructor = Uint8Array; + private _channels$ = 4; + private _alignment$ = 1; public constructor (device: Device) { - this._device = device; + this._device$ = device; } public initialize (info: ITextureBufferPoolInfo): void { const formatInfo = FormatInfos[info.format]; - this._format = info.format; - this._formatSize = formatInfo.size; - this._channels = formatInfo.count; - this._bufferViewCtor = getTypedArrayConstructor(formatInfo); - this._roundUpFn = info.roundUpFn || null; - this._alignment = info.alignment || 1; - if (info.inOrderFree) { this.alloc = this._McDonaldAlloc; } + this._format$ = info.format; + this._formatSize$ = formatInfo.size; + this._channels$ = formatInfo.count; + this._bufferViewCtor$ = getTypedArrayConstructor(formatInfo); + this._roundUpFn$ = info.roundUpFn || null; + this._alignment$ = info.alignment || 1; + if (info.inOrderFree) { this.alloc = this._McDonaldAlloc$; } } public destroy (): void { - for (let i = 0; i < this._chunkCount; ++i) { - const chunk = this._chunks[i]; + for (let i = 0; i < this._chunkCount$; ++i) { + const chunk = this._chunks$[i]; chunk.texture.destroy(); } - this._chunks.length = 0; - this._handles.length = 0; + this._chunks$.length = 0; + this._handles$.length = 0; } public alloc (size: number, chunkIdx?: number): ITextureBufferHandle { - size = roundUp(size, this._alignment); + size = roundUp(size, this._alignment$); let index = -1; let start = -1; if (chunkIdx !== undefined) { index = chunkIdx; - start = this._findAvailableSpace(size, index); + start = this._findAvailableSpace$(size, index); } if (start < 0) { - for (let i = 0; i < this._chunkCount; ++i) { + for (let i = 0; i < this._chunkCount$; ++i) { index = i; - start = this._findAvailableSpace(size, index); + start = this._findAvailableSpace$(size, index); if (start >= 0) { break; } } } if (start >= 0) { - const chunk = this._chunks[index]; + const chunk = this._chunks$[index]; chunk.start += size; const handle: ITextureBufferHandle = { chunkIdx: index, @@ -128,45 +128,45 @@ export class TextureBufferPool { end: start + size, texture: chunk.texture, }; - this._handles.push(handle); + this._handles$.push(handle); return handle; } // create a new one - const targetSize = Math.sqrt(size / this._formatSize); - const texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize)); - const newChunk = this._chunks[this.createChunk(texLength)]; + const targetSize = Math.sqrt(size / this._formatSize$); + const texLength = this._roundUpFn$ && this._roundUpFn$(targetSize, this._formatSize$) || Math.max(1024, nearestPOT(targetSize)); + const newChunk = this._chunks$[this.createChunk(texLength)]; newChunk.start += size; const texHandle: ITextureBufferHandle = { - chunkIdx: this._chunkCount - 1, + chunkIdx: this._chunkCount$ - 1, start: 0, end: size, texture: newChunk.texture, }; - this._handles.push(texHandle); + this._handles$.push(texHandle); return texHandle; } public free (handle: ITextureBufferHandle): void { - for (let i = 0; i < this._handles.length; ++i) { - if (this._handles[i] === handle) { - this._chunks[handle.chunkIdx].end = handle.end; - this._handles.splice(i, 1); + for (let i = 0; i < this._handles$.length; ++i) { + if (this._handles$[i] === handle) { + this._chunks$[handle.chunkIdx].end = handle.end; + this._handles$.splice(i, 1); return; } } } public createChunk (length: number): number { - const texSize = length * length * this._formatSize; + const texSize = length * length * this._formatSize$; - debug(`TextureBufferPool: Allocate chunk ${this._chunkCount}, size: ${texSize}, format: ${this._format}`); + debug(`TextureBufferPool: Allocate chunk ${this._chunkCount$}, size: ${texSize}, format: ${this._format$}`); - const texture: Texture = this._device.createTexture(new TextureInfo( + const texture: Texture = this._device$.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, - this._format, + this._format$, length, length, )); @@ -177,29 +177,29 @@ export class TextureBufferPool { start: 0, end: texSize, }; - this._chunks[this._chunkCount] = chunk; - return this._chunkCount++; + this._chunks$[this._chunkCount$] = chunk; + return this._chunkCount$++; } public update (handle: ITextureBufferHandle, buffer: ArrayBuffer): void { const buffers: ArrayBufferView[] = []; const regions: BufferTextureCopy[] = []; - const start = handle.start / this._formatSize; + const start = handle.start / this._formatSize$; - let remainSize = buffer.byteLength / this._formatSize; + let remainSize = buffer.byteLength / this._formatSize$; let offsetX = start % handle.texture.width; let offsetY = Math.floor(start / handle.texture.width); let copySize = Math.min(handle.texture.width - offsetX, remainSize); let begin = 0; if (offsetX > 0) { - this._region0.texOffset.x = offsetX; - this._region0.texOffset.y = offsetY; - this._region0.texExtent.width = copySize; - this._region0.texExtent.height = 1; + this._region0$.texOffset.x = offsetX; + this._region0$.texOffset.y = offsetY; + this._region0$.texExtent.width = copySize; + this._region0$.texExtent.height = 1; - buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels)); - regions.push(this._region0); + buffers.push(new this._bufferViewCtor$(buffer, begin * this._formatSize$, copySize * this._channels$)); + regions.push(this._region0$); offsetX = 0; offsetY += 1; @@ -208,50 +208,50 @@ export class TextureBufferPool { } if (remainSize > 0) { - this._region1.texOffset.x = offsetX; - this._region1.texOffset.y = offsetY; + this._region1$.texOffset.x = offsetX; + this._region1$.texOffset.y = offsetY; if (remainSize > handle.texture.width) { - this._region1.texExtent.width = handle.texture.width; - this._region1.texExtent.height = Math.floor(remainSize / handle.texture.width); - copySize = this._region1.texExtent.width * this._region1.texExtent.height; + this._region1$.texExtent.width = handle.texture.width; + this._region1$.texExtent.height = Math.floor(remainSize / handle.texture.width); + copySize = this._region1$.texExtent.width * this._region1$.texExtent.height; } else { copySize = remainSize; - this._region1.texExtent.width = copySize; - this._region1.texExtent.height = 1; + this._region1$.texExtent.width = copySize; + this._region1$.texExtent.height = 1; } - buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels)); - regions.push(this._region1); + buffers.push(new this._bufferViewCtor$(buffer, begin * this._formatSize$, copySize * this._channels$)); + regions.push(this._region1$); offsetX = 0; - offsetY += this._region1.texExtent.height; + offsetY += this._region1$.texExtent.height; remainSize -= copySize; begin += copySize; } if (remainSize > 0) { - this._region2.texOffset.x = offsetX; - this._region2.texOffset.y = offsetY; - this._region2.texExtent.width = remainSize; - this._region2.texExtent.height = 1; + this._region2$.texOffset.x = offsetX; + this._region2$.texOffset.y = offsetY; + this._region2$.texExtent.width = remainSize; + this._region2$.texExtent.height = 1; - buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, remainSize * this._channels)); - regions.push(this._region2); + buffers.push(new this._bufferViewCtor$(buffer, begin * this._formatSize$, remainSize * this._channels$)); + regions.push(this._region2$); } - this._device.copyBuffersToTexture(buffers, handle.texture, regions); + this._device$.copyBuffersToTexture(buffers, handle.texture, regions); } - private _findAvailableSpace (size: number, chunkIdx: number): number { - const chunk = this._chunks[chunkIdx]; + private _findAvailableSpace$ (size: number, chunkIdx: number): number { + const chunk = this._chunks$[chunkIdx]; let isFound = false; let start = chunk.start; if ((start + size) <= chunk.size) { isFound = true; } else { start = 0; // try to find from head again - const handles = this._handles.filter((h): boolean => h.chunkIdx === chunkIdx).sort((a, b): number => a.start - b.start); + const handles = this._handles$.filter((h): boolean => h.chunkIdx === chunkIdx).sort((a, b): number => a.start - b.start); for (let i = 0; i < handles.length; i++) { const handle = handles[i]; if ((start + size) <= handle.start) { @@ -268,11 +268,11 @@ export class TextureBufferPool { } // [McDonald 12] Efficient Buffer Management - private _McDonaldAlloc (size: number): ITextureBufferHandle { - size = roundUp(size, this._alignment); + private _McDonaldAlloc$ (size: number): ITextureBufferHandle { + size = roundUp(size, this._alignment$); - for (let i = 0; i < this._chunkCount; ++i) { - const chunk = this._chunks[i]; + for (let i = 0; i < this._chunkCount$; ++i) { + const chunk = this._chunks$[i]; let isFound = false; let start = chunk.start; if ((start + size) <= chunk.end) { @@ -300,24 +300,24 @@ export class TextureBufferPool { end: start + size, texture: chunk.texture, }; - this._handles.push(handle); + this._handles$.push(handle); return handle; } } // create a new one - const targetSize = Math.sqrt(size / this._formatSize); - const texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize)); - const newChunk = this._chunks[this.createChunk(texLength)]; + const targetSize = Math.sqrt(size / this._formatSize$); + const texLength = this._roundUpFn$ && this._roundUpFn$(targetSize, this._formatSize$) || Math.max(1024, nearestPOT(targetSize)); + const newChunk = this._chunks$[this.createChunk(texLength)]; newChunk.start += size; const texHandle: ITextureBufferHandle = { - chunkIdx: this._chunkCount, + chunkIdx: this._chunkCount$, start: 0, end: size, texture: newChunk.texture, }; - this._handles.push(texHandle); + this._handles$.push(texHandle); return texHandle; } } diff --git a/cocos/render-scene/scene/camera.jsb.ts b/cocos/render-scene/scene/camera.jsb.ts index 15e2da4c92e..e7ac4a39b84 100644 --- a/cocos/render-scene/scene/camera.jsb.ts +++ b/cocos/render-scene/scene/camera.jsb.ts @@ -123,7 +123,11 @@ export interface ICameraInfo { trackingType?: TrackingType; } -export const SKYBOX_FLAG = ClearFlagBit.STENCIL << 1; +export enum SkyBoxFlagValue { + VALUE = ClearFlagBit.STENCIL << 1, +} + +export const SKYBOX_FLAG = SkyBoxFlagValue.VALUE; export const Camera: typeof JsbCamera = jsb.Camera; export type Camera = JsbCamera; diff --git a/cocos/render-scene/scene/camera.ts b/cocos/render-scene/scene/camera.ts index 64c7247d161..5ddbf147879 100644 --- a/cocos/render-scene/scene/camera.ts +++ b/cocos/render-scene/scene/camera.ts @@ -23,7 +23,7 @@ */ import { EDITOR } from 'internal:constants'; import { SurfaceTransform, ClearFlagBit, Device, Color, ClearFlags } from '../../gfx'; -import { lerp, Mat4, Rect, toRadian, Vec3, IVec4Like, preTransforms, warnID, geometry, cclegacy, Vec4 } from '../../core'; +import { lerp, Mat4, Rect, toRadian, Vec3, IVec4Like, preTransforms, warnID, geometry, cclegacy, Vec4, rect, mat4, v3 } from '../../core'; import { CAMERA_DEFAULT_MASK } from '../../rendering/define'; import { Node } from '../../scene-graph'; import { RenderScene } from '../core/render-scene'; @@ -390,7 +390,11 @@ const v_a = new Vec3(); const v_b = new Vec3(); const _tempMat1 = new Mat4(); -export const SKYBOX_FLAG = ClearFlagBit.STENCIL << 1; +export enum SkyBoxFlagValue { + VALUE = ClearFlagBit.STENCIL << 1, +} + +export const SKYBOX_FLAG = SkyBoxFlagValue.VALUE; const correctionMatrices: Mat4[] = []; @@ -420,7 +424,7 @@ export class Camera { * @zh 相机的名称 */ get name (): string | null { - return this._name; + return this._name$; } /** @@ -428,7 +432,7 @@ export class Camera { * @zh 相机所挂载的场景 */ get scene (): RenderScene | null { - return this._scene; + return this._scene$; } /** @@ -436,10 +440,10 @@ export class Camera { * @zh 相机绑定的节点,决定了它在世界空间的变换矩阵 */ set node (val: Node) { - this._node = val; + this._node$ = val; } get node (): Node { - return this._node!; + return this._node$!; } /** @@ -447,7 +451,7 @@ export class Camera { * @zh 相机关联的渲染窗口ID */ get systemWindowId (): number { - return this._windowId; + return this._windowId$; } /** @@ -455,10 +459,10 @@ export class Camera { * @zh 相机关联的渲染窗口 */ set window (val) { - this._window = val; + this._window$ = val; } get window (): RenderWindow { - return this._window!; + return this._window$!; } /** @@ -466,10 +470,10 @@ export class Camera { * @zh 相机是否启用,未启用的相机不会被渲染 */ set enabled (val) { - this._enabled = val; + this._enabled$ = val; } get enabled (): boolean { - return this._enabled; + return this._enabled$; } /** @@ -477,10 +481,10 @@ export class Camera { * @zh 相机的可见性掩码,声明在当前相机中可见的节点层级集合。 */ set visibility (vis: number) { - this._visibility = vis; + this._visibility$ = vis; } get visibility (): number { - return this._visibility; + return this._visibility$; } /** @@ -488,11 +492,11 @@ export class Camera { * @zh 相机的渲染优先级,值越小越优先渲染。 */ get priority (): number { - return this._priority; + return this._priority$; } set priority (val: number) { - this._priority = val; + this._priority$ = val; } /** @@ -500,7 +504,7 @@ export class Camera { * @zh 相机的视图宽度 */ get width (): number { - return this._width; + return this._width$; } /** @@ -508,7 +512,7 @@ export class Camera { * @zh 相机的视图高度 */ get height (): number { - return this._height; + return this._height$; } /** @@ -516,10 +520,10 @@ export class Camera { * @zh 相机的世界坐标 */ set position (val) { - this._position = val; + this._position$ = val; } get position (): Vec3 { - return this._position; + return this._position$; } /** @@ -527,10 +531,10 @@ export class Camera { * @zh 指向相机观察方向的向量 */ set forward (val) { - this._forward = val; + this._forward$ = val; } get forward (): Vec3 { - return this._forward; + return this._forward$; } /** @@ -538,12 +542,12 @@ export class Camera { * @zh 相机光圈,影响相机的曝光参数。 */ set aperture (val: CameraAperture) { - this._aperture = val; - this._apertureValue = FSTOPS[this._aperture]; - this.updateExposure(); + this._aperture$ = val; + this._apertureValue$ = FSTOPS[this._aperture$]; + this.updateExposure$(); } get aperture (): CameraAperture { - return this._aperture; + return this._aperture$; } /** @@ -551,7 +555,7 @@ export class Camera { * @zh 相机光圈值。 */ get apertureValue (): number { - return this._apertureValue; + return this._apertureValue$; } /** @@ -559,12 +563,12 @@ export class Camera { * @zh 相机快门,影响相机的曝光参数。 */ set shutter (val: CameraShutter) { - this._shutter = val; - this._shutterValue = SHUTTERS[this._shutter]; - this.updateExposure(); + this._shutter$ = val; + this._shutterValue$ = SHUTTERS[this._shutter$]; + this.updateExposure$(); } get shutter (): CameraShutter { - return this._shutter; + return this._shutter$; } /** @@ -572,7 +576,7 @@ export class Camera { * @zh 相机快门值。 */ get shutterValue (): number { - return this._shutterValue; + return this._shutterValue$; } /** @@ -581,8 +585,8 @@ export class Camera { */ set iso (val: CameraISO) { this._iso = val; - this._isoValue = ISOS[this._iso]; - this.updateExposure(); + this._isoValue$ = ISOS[this._iso]; + this.updateExposure$(); } get iso (): CameraISO { return this._iso; @@ -593,7 +597,7 @@ export class Camera { * @zh 相机感光度值。 */ get isoValue (): number { - return this._isoValue; + return this._isoValue$; } /** @@ -601,7 +605,7 @@ export class Camera { * @zh 相机的曝光参数 */ get exposure (): number { - return this._exposure; + return this._exposure$; } /** @@ -609,10 +613,10 @@ export class Camera { * @zh 相机的缓冲清除标志位,指定帧缓冲的哪部分要每帧清除。 */ get clearFlag (): ClearFlags { - return this._clearFlag; + return this._clearFlag$; } set clearFlag (flag: ClearFlags) { - this._clearFlag = flag; + this._clearFlag$ = flag; } /** @@ -620,13 +624,13 @@ export class Camera { * @zh 相机的颜色缓冲默认值。 */ set clearColor (val) { - this._clearColor.x = val.x; - this._clearColor.y = val.y; - this._clearColor.z = val.z; - this._clearColor.w = val.w; + this._clearColor$.x = val.x; + this._clearColor$.y = val.y; + this._clearColor$.z = val.z; + this._clearColor$.w = val.w; } get clearColor (): IVec4Like { - return this._clearColor as IVec4Like; + return this._clearColor$ as IVec4Like; } /** @@ -634,10 +638,10 @@ export class Camera { * @zh 相机的深度缓冲默认值。 */ get clearDepth (): number { - return this._clearDepth; + return this._clearDepth$; } set clearDepth (depth: number) { - this._clearDepth = depth; + this._clearDepth$ = depth; } /** @@ -645,10 +649,10 @@ export class Camera { * @zh 相机的模板缓冲默认值。 */ get clearStencil (): number { - return this._clearStencil; + return this._clearStencil$; } set clearStencil (stencil: number) { - this._clearStencil = stencil; + this._clearStencil$ = stencil; } /** @@ -656,11 +660,11 @@ export class Camera { * @zh 相机的投影类型。 */ set projectionType (val) { - this._proj = val; - this._isProjDirty = true; + this._proj$ = val; + this._isProjDirty$ = true; } get projectionType (): CameraProjection { - return this._proj; + return this._proj$; } /** @@ -668,7 +672,7 @@ export class Camera { * @zh 相机视图的长宽比 */ get aspect (): number { - return this._aspect; + return this._aspect$; } /** @@ -676,11 +680,11 @@ export class Camera { * @zh 正交相机的视角高度。 */ set orthoHeight (val) { - this._orthoHeight = val; - this._isProjDirty = true; + this._orthoHeight$ = val; + this._isProjDirty$ = true; } get orthoHeight (): number { - return this._orthoHeight; + return this._orthoHeight$; } /** @@ -688,11 +692,11 @@ export class Camera { * @zh 指定视角的固定轴向,在此轴上不会跟随屏幕长宽比例变化。 */ set fovAxis (axis) { - this._fovAxis = axis; - this._isProjDirty = true; + this._fovAxis$ = axis; + this._isProjDirty$ = true; } get fovAxis (): CameraFOVAxis { - return this._fovAxis; + return this._fovAxis$; } /** @@ -700,11 +704,11 @@ export class Camera { * @zh 相机的视角大小。 */ set fov (fov) { - this._fov = fov; - this._isProjDirty = true; + this._fov$ = fov; + this._isProjDirty$ = true; } get fov (): number { - return this._fov; + return this._fov$; } /** @@ -712,11 +716,11 @@ export class Camera { * @zh 相机的近裁剪距离,应在可接受范围内尽量取最大。 */ set nearClip (nearClip) { - this._nearClip = nearClip; - this._isProjDirty = true; + this._nearClip$ = nearClip; + this._isProjDirty$ = true; } get nearClip (): number { - return this._nearClip; + return this._nearClip$; } /** @@ -724,11 +728,11 @@ export class Camera { * @zh 相机的远裁剪距离,应在可接受范围内尽量取最小。 */ set farClip (farClip) { - this._farClip = farClip; - this._isProjDirty = true; + this._farClip$ = farClip; + this._isProjDirty$ = true; } get farClip (): number { - return this._farClip; + return this._farClip$; } /** @@ -736,7 +740,7 @@ export class Camera { * @zh 相机的视口矩形,如果设备允许的话,这个视口会永远保持竖屏状态,由渲染流程保障旋转的正确。 */ get viewport (): Rect { - return this._viewport; + return this._viewport$; } set viewport (val) { warnID(8302); @@ -748,10 +752,10 @@ export class Camera { * @zh 相机的视锥体 */ set frustum (val) { - this._frustum = val; + this._frustum$ = val; } get frustum (): Frustum { - return this._frustum; + return this._frustum$; } /** @@ -759,7 +763,7 @@ export class Camera { * @zh 相机的视图矩阵 */ get matView (): Mat4 { - return this._matView; + return this._matView$; } /** @@ -767,7 +771,7 @@ export class Camera { * @zh 相机的投影矩阵 */ get matProj (): Mat4 { - return this._matProj; + return this._matProj$; } /** @@ -775,7 +779,7 @@ export class Camera { * @zh 相机的逆投影矩阵 */ get matProjInv (): Mat4 { - return this._matProjInv; + return this._matProjInv$; } /** @@ -783,7 +787,7 @@ export class Camera { * @zh 相机的视图投影矩阵 */ get matViewProj (): Mat4 { - return this._matViewProj; + return this._matViewProj$; } /** @@ -791,7 +795,7 @@ export class Camera { * @zh 相机的逆视图投影矩阵 */ get matViewProjInv (): Mat4 { - return this._matViewProjInv; + return this._matViewProjInv$; } /** @@ -812,59 +816,59 @@ export class Camera { public pipeline = ''; public pipelineSettings: object | null = null; - private declare _device: Device; - private _scene: RenderScene | null = null; - private _node: Node | null = null; - private _name: string | null = null; - private _enabled = false; - private _proj: CameraProjection = -1; - private _aspect: number = 1; - private _orthoHeight = 10.0; - private _fovAxis = CameraFOVAxis.VERTICAL; - private _fov: number = toRadian(45); - private _nearClip = 1.0; - private _farClip = 1000.0; - private _clearColor = new Color(0.2, 0.2, 0.2, 1); - private _viewport: Rect = new Rect(0, 0, 1, 1); - private _orientedViewport: Rect = new Rect(0, 0, 1, 1); - private _curTransform = SurfaceTransform.IDENTITY; - private _isProjDirty = true; - private _matView: Mat4 = new Mat4(); - private _matProj: Mat4 = new Mat4(); - private _matProjInv: Mat4 = new Mat4(); - private _matViewProj: Mat4 = new Mat4(); - private _matViewProjInv: Mat4 = new Mat4(); - private _frustum: geometry.Frustum = new geometry.Frustum(); - private _forward: Vec3 = new Vec3(); - private _position: Vec3 = new Vec3(); - private _priority = 0; - private _aperture: CameraAperture = CameraAperture.F16_0; - private declare _apertureValue: number; - private _shutter: CameraShutter = CameraShutter.D125; - private _shutterValue = 0.0; + private declare _device$: Device; + private _scene$: RenderScene | null = null; + private _node$: Node | null = null; + private _name$: string | null = null; + private _enabled$ = false; + private _proj$: CameraProjection = -1 as CameraProjection; + private _aspect$: number = 1; + private _orthoHeight$ = 10.0; + private _fovAxis$ = CameraFOVAxis.VERTICAL; + private _fov$: number = toRadian(45); + private _nearClip$ = 1.0; + private _farClip$ = 1000.0; + private _clearColor$ = new Color(0.2, 0.2, 0.2, 1); + private _viewport$: Rect = rect(0, 0, 1, 1); + private _orientedViewport$: Rect = rect(0, 0, 1, 1); + private _curTransform$ = SurfaceTransform.IDENTITY; + private _isProjDirty$ = true; + private _matView$: Mat4 = mat4(); + private _matProj$: Mat4 = mat4(); + private _matProjInv$: Mat4 = mat4(); + private _matViewProj$: Mat4 = mat4(); + private _matViewProjInv$: Mat4 = mat4(); + private _frustum$: geometry.Frustum = new geometry.Frustum(); + private _forward$: Vec3 = v3(); + private _position$: Vec3 = v3(); + private _priority$ = 0; + private _aperture$: CameraAperture = CameraAperture.F16_0; + private declare _apertureValue$: number; + private _shutter$: CameraShutter = CameraShutter.D125; + private _shutterValue$ = 0.0; private _iso: CameraISO = CameraISO.ISO100; - private _isoValue = 0.0; - private _window: RenderWindow | null = null; - private _width = 1; - private _height = 1; - private _clearFlag = ClearFlagBit.NONE; - private _clearDepth = 1.0; - private _visibility = CAMERA_DEFAULT_MASK; - private _exposure = 0; - private _clearStencil = 0; - private _geometryRenderer: GeometryRenderer | null = null; - private _windowId = 0; - private _cameraType: CameraType = CameraType.DEFAULT; - private _trackingType: TrackingType = TrackingType.NO_TRACKING; - private _usage: CameraUsage = CameraUsage.GAME; + private _isoValue$ = 0.0; + private _window$: RenderWindow | null = null; + private _width$ = 1; + private _height$ = 1; + private _clearFlag$ = ClearFlagBit.NONE; + private _clearDepth$ = 1.0; + private _visibility$ = CAMERA_DEFAULT_MASK; + private _exposure$ = 0; + private _clearStencil$ = 0; + private _geometryRenderer$: GeometryRenderer | null = null; + private _windowId$ = 0; + private _cameraType$: CameraType = CameraType.DEFAULT; + private _trackingType$: TrackingType = TrackingType.NO_TRACKING; + private _usage$: CameraUsage = CameraUsage.GAME; constructor (device: Device) { - this._device = device; - this._apertureValue = FSTOPS[this._aperture]; - this._shutterValue = SHUTTERS[this._shutter]; - this._isoValue = ISOS[this._iso]; + this._device$ = device; + this._apertureValue$ = FSTOPS[this._aperture$]; + this._shutterValue$ = SHUTTERS[this._shutter$]; + this._isoValue$ = ISOS[this._iso]; - this._frustum.accurate = true; + this._frustum$.accurate = true; if (!correctionMatrices.length) { const ySign = device.capabilities.clipSpaceSignY; @@ -875,15 +879,15 @@ export class Camera { } } - private _updateAspect (oriented = true): void { - this._aspect = (this.window.width * this._viewport.width) / (this.window.height * this._viewport.height); + private _updateAspect$ (oriented = true): void { + this._aspect$ = (this.window.width * this._viewport$.width) / (this.window.height * this._viewport$.height); // window size/viewport is pre-rotated, but aspect should be oriented to acquire the correct projection if (oriented) { const swapchain = this.window.swapchain; const orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY; - if (orientation % 2) this._aspect = 1 / this._aspect; + if (orientation % 2) this._aspect$ = 1 / this._aspect$; } - this._isProjDirty = true; + this._isProjDirty$ = true; } /** @@ -892,27 +896,27 @@ export class Camera { */ public initialize (info: ICameraInfo): void { if (info.usage !== undefined) { - this._usage = info.usage; + this._usage$ = info.usage; } else { - this.setDefaultUsage(); + this.setDefaultUsage$(); } if (info.trackingType !== undefined) { - this._trackingType = info.trackingType; + this._trackingType$ = info.trackingType; } if (info.cameraType !== undefined) { - this._cameraType = info.cameraType; + this._cameraType$ = info.cameraType; } this.node = info.node; - this._width = 1; - this._height = 1; + this._width$ = 1; + this._height$ = 1; this.clearFlag = ClearFlagBit.NONE; this.clearDepth = 1.0; this.visibility = CAMERA_DEFAULT_MASK; - this._name = info.name; - this._proj = info.projection; - this._priority = info.priority || 0; - this._aspect = this.screenScale = 1; - this.updateExposure(); + this._name$ = info.name; + this._proj$ = info.projection; + this._priority$ = info.priority || 0; + this._aspect$ = this.screenScale = 1; + this.updateExposure$(); this.changeTargetWindow(info.window); } @@ -921,14 +925,14 @@ export class Camera { * @zh 销毁相机,开发者不应该使用这个方法,销毁流程是由 RenderScene 管理的。 */ public destroy (): void { - this._node = null; + this._node$ = null; this.detachFromScene(); - if (this._window) { - this._window.detachCamera(this); + if (this._window$) { + this._window$.detachCamera(this); this.window = null!; } - this._name = null; - this._geometryRenderer?.destroy(); + this._name$ = null; + this._geometryRenderer$?.destroy(); } /** @@ -937,8 +941,8 @@ export class Camera { * @param scene @en The render scene @zh 渲染场景 */ public attachToScene (scene: RenderScene): void { - this._enabled = true; - this._scene = scene; + this._enabled$ = true; + this._scene$ = scene; } /** @@ -946,8 +950,8 @@ export class Camera { * @zh 将相机从之前设置的渲染场景移除,之后将不会再被渲染。 */ public detachFromScene (): void { - this._enabled = false; - this._scene = null; + this._enabled$ = false; + this._scene$ = null; } /** @@ -957,12 +961,12 @@ export class Camera { * @param height The height of the view size */ public resize (width: number, height: number): void { - if (!this._window) return; + if (!this._window$) return; - this._width = width; - this._height = height; - this._aspect = (width * this._viewport.width) / (height * this._viewport.height); - this._isProjDirty = true; + this._width$ = width; + this._height$ = height; + this._aspect$ = (width * this._viewport$.width) / (height * this._viewport$.height); + this._isProjDirty$ = true; } /** @@ -972,9 +976,9 @@ export class Camera { * @param height The height of the view size */ public setFixedSize (width: number, height: number): void { - this._width = width; - this._height = height; - this._updateAspect(); + this._width$ = width; + this._height$ = height; + this._updateAspect$(); this.isWindowSize = false; } @@ -986,10 +990,10 @@ export class Camera { if (EDITOR) { this.position = camera.position; this.forward = camera.forward; - this._matView = camera.matView; - this._matProj = camera.matProj; - this._matProjInv = camera.matProjInv; - this._matViewProj = camera.matViewProj; + this._matView$ = camera.matView; + this._matProj$ = camera.matProj; + this._matProjInv$ = camera.matProjInv; + this._matViewProj$ = camera.matViewProj; } } @@ -999,82 +1003,82 @@ export class Camera { * @param forceUpdate If force update, then dirty flag will be ignored */ public update (forceUpdate = false): void { // for lazy eval situations like the in-editor preview - if (!this._node) return; + if (!this._node$) return; let viewProjDirty = false; const xr = globalThis.__globalXR; if (xr && xr.isWebXR && xr.webXRWindowMap && xr.updateViewport) { const x = xr.webXRMatProjs ? 1 / xr.webXRMatProjs.length : 1; - const wndXREye = xr.webXRWindowMap.get(this._window); + const wndXREye = xr.webXRWindowMap.get(this._window$); this.setViewportInOrientedSpace(new Rect(x * wndXREye, 0, x, 1)); } // view matrix - if (this._node.hasChangedFlags || forceUpdate) { - Mat4.invert(this._matView, this._node.worldMatrix); - this._forward.x = -this._matView.m02; - this._forward.y = -this._matView.m06; - this._forward.z = -this._matView.m10; + if (this._node$.hasChangedFlags || forceUpdate) { + Mat4.invert(this._matView$, this._node$.worldMatrix); + this._forward$.x = -this._matView$.m02; + this._forward$.y = -this._matView$.m06; + this._forward$.z = -this._matView$.m10; // Remove scale - Mat4.multiply(this._matView, new Mat4().scale(this._node.worldScale), this._matView); - this._node.getWorldPosition(this._position); + Mat4.multiply(this._matView$, new Mat4().scale(this._node$.worldScale), this._matView$); + this._node$.getWorldPosition(this._position$); viewProjDirty = true; } // projection matrix const swapchain = this.window?.swapchain; const orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY; - if (this._isProjDirty || this._curTransform !== orientation) { - this._curTransform = orientation; - const projectionSignY = this._device.capabilities.clipSpaceSignY; + if (this._isProjDirty$ || this._curTransform$ !== orientation) { + this._curTransform$ = orientation; + const projectionSignY = this._device$.capabilities.clipSpaceSignY; // Only for rendertexture processing - if (this._proj === CameraProjection.PERSPECTIVE) { + if (this._proj$ === CameraProjection.PERSPECTIVE) { if (xr && xr.isWebXR && xr.webXRWindowMap && xr.webXRMatProjs) { - const wndXREye = xr.webXRWindowMap.get(this._window); - this._matProj.set(xr.webXRMatProjs[wndXREye]); + const wndXREye = xr.webXRWindowMap.get(this._window$); + this._matProj$.set(xr.webXRMatProjs[wndXREye]); } else { Mat4.perspective( - this._matProj, - this._fov, - this._aspect, - this._nearClip, - this._farClip, - this._fovAxis === CameraFOVAxis.VERTICAL, - this._device.capabilities.clipSpaceMinZ, + this._matProj$, + this._fov$, + this._aspect$, + this._nearClip$, + this._farClip$, + this._fovAxis$ === CameraFOVAxis.VERTICAL, + this._device$.capabilities.clipSpaceMinZ, projectionSignY, orientation, ); } } else { - const x = this._orthoHeight * this._aspect; - const y = this._orthoHeight; + const x = this._orthoHeight$ * this._aspect$; + const y = this._orthoHeight$; Mat4.ortho( - this._matProj, + this._matProj$, -x, x, -y, y, - this._nearClip, - this._farClip, - this._device.capabilities.clipSpaceMinZ, + this._nearClip$, + this._farClip$, + this._device$.capabilities.clipSpaceMinZ, projectionSignY, orientation, ); } - Mat4.invert(this._matProjInv, this._matProj); + Mat4.invert(this._matProjInv$, this._matProj$); viewProjDirty = true; - this._isProjDirty = false; + this._isProjDirty$ = false; } // view-projection if (viewProjDirty) { - Mat4.multiply(this._matViewProj, this._matProj, this._matView); - Mat4.invert(this._matViewProjInv, this._matViewProj); - this._frustum.update(this._matViewProj, this._matViewProjInv); + Mat4.multiply(this._matViewProj$, this._matProj$, this._matView$); + Mat4.invert(this._matViewProjInv$, this._matViewProj$); + this._frustum$.update(this._matViewProj$, this._matViewProjInv$); } } get surfaceTransform (): SurfaceTransform { - return this._curTransform; + return this._curTransform$; } /** @@ -1083,43 +1087,43 @@ export class Camera { */ public setViewportInOrientedSpace (val: Rect): void { const { x, width, height } = val; - const y = this._device.capabilities.screenSpaceSignY < 0 ? 1 - val.y - height : val.y; + const y = this._device$.capabilities.screenSpaceSignY < 0 ? 1 - val.y - height : val.y; const swapchain = this.window?.swapchain; const orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY; switch (orientation) { case SurfaceTransform.ROTATE_90: - this._viewport.x = 1 - y - height; - this._viewport.y = x; - this._viewport.width = height; - this._viewport.height = width; + this._viewport$.x = 1 - y - height; + this._viewport$.y = x; + this._viewport$.width = height; + this._viewport$.height = width; break; case SurfaceTransform.ROTATE_180: - this._viewport.x = 1 - x - width; - this._viewport.y = 1 - y - height; - this._viewport.width = width; - this._viewport.height = height; + this._viewport$.x = 1 - x - width; + this._viewport$.y = 1 - y - height; + this._viewport$.width = width; + this._viewport$.height = height; break; case SurfaceTransform.ROTATE_270: - this._viewport.x = y; - this._viewport.y = 1 - x - width; - this._viewport.width = height; - this._viewport.height = width; + this._viewport$.x = y; + this._viewport$.y = 1 - x - width; + this._viewport$.width = height; + this._viewport$.height = width; break; case SurfaceTransform.IDENTITY: - this._viewport.x = x; - this._viewport.y = y; - this._viewport.width = width; - this._viewport.height = height; + this._viewport$.x = x; + this._viewport$.y = y; + this._viewport$.width = width; + this._viewport$.height = height; break; default: } - this._orientedViewport.x = x; - this._orientedViewport.y = y; - this._orientedViewport.width = width; - this._orientedViewport.height = height; + this._orientedViewport$.x = x; + this._orientedViewport$.y = y; + this._orientedViewport$.width = width; + this._orientedViewport$.height = height; this.resize(this.width, this.height); } @@ -1129,9 +1133,9 @@ export class Camera { * @zh 创建这个摄像机的几何体渲染器 */ public initGeometryRenderer (): void { - if (!this._geometryRenderer) { - this._geometryRenderer = cclegacy.internal.GeometryRenderer ? new cclegacy.internal.GeometryRenderer() : null; - this._geometryRenderer?.activate(this._device); + if (!this._geometryRenderer$) { + this._geometryRenderer$ = cclegacy.internal.GeometryRenderer ? new cclegacy.internal.GeometryRenderer() : null; + this._geometryRenderer$?.activate(this._device$); } } @@ -1141,31 +1145,31 @@ export class Camera { * @returns @en return the geometry renderer @zh 返回几何体渲染器 */ get geometryRenderer (): GeometryRenderer | null { - return this._geometryRenderer; + return this._geometryRenderer$; } get cameraType (): CameraType { - return this._cameraType; + return this._cameraType$; } set cameraType (type: CameraType) { - this._cameraType = type; + this._cameraType$ = type; } get trackingType (): TrackingType { - return this._trackingType; + return this._trackingType$; } set trackingType (type: TrackingType) { - this._trackingType = type; + this._trackingType$ = type; } get cameraUsage (): CameraUsage { - return this._usage; + return this._usage$; } set cameraUsage (usage: CameraUsage) { - this._usage = usage; + this._usage$ = usage; } /** @@ -1174,8 +1178,8 @@ export class Camera { * @param window The target render window, could be null */ public changeTargetWindow (window: RenderWindow | null = null): void { - if (this._window) { - this._window.detachCamera(this); + if (this._window$) { + this._window$.detachCamera(this); } const win = window || cclegacy.director.root.mainWindow; if (win) { @@ -1195,8 +1199,8 @@ export class Camera { * @zh 将 camera 从渲染窗口移除 */ public detachCamera (): void { - if (this._window) { - this._window.detachCamera(this); + if (this._window$) { + this._window$.detachCamera(this); } } @@ -1209,17 +1213,17 @@ export class Camera { * @returns the resulting ray */ public screenPointToRay (out: geometry.Ray, x: number, y: number): geometry.Ray { - if (!this._node) return null!; + if (!this._node$) return null!; const width = this.width; const height = this.height; - const cx = this._orientedViewport.x * width; - const cy = this._orientedViewport.y * height; - const cw = this._orientedViewport.width * width; - const ch = this._orientedViewport.height * height; - const isProj = this._proj === CameraProjection.PERSPECTIVE; - const ySign = this._device.capabilities.clipSpaceSignY; - const preTransform = preTransforms[this._curTransform]; + const cx = this._orientedViewport$.x * width; + const cy = this._orientedViewport$.y * height; + const cw = this._orientedViewport$.width * width; + const ch = this._orientedViewport$.height * height; + const isProj = this._proj$ === CameraProjection.PERSPECTIVE; + const ySign = this._device$.capabilities.clipSpaceSignY; + const preTransform = preTransforms[this._curTransform$]; Vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, isProj ? 1 : -1); @@ -1227,14 +1231,14 @@ export class Camera { v_a.x = ox * preTransform[0] + oy * preTransform[2] * ySign; v_a.y = ox * preTransform[1] + oy * preTransform[3] * ySign; - Vec3.transformMat4(isProj ? v_a : out.o, v_a, this._matViewProjInv); + Vec3.transformMat4(isProj ? v_a : out.o, v_a, this._matViewProjInv$); if (isProj) { // camera origin - this._node.getWorldPosition(v_b); + this._node$.getWorldPosition(v_b); geometry.Ray.fromPoints(out, v_b, v_a); } else { - Vec3.transformQuat(out.d, Vec3.FORWARD, this._node.worldRotation); + Vec3.transformQuat(out.d, Vec3.FORWARD, this._node$.worldRotation); } return out; @@ -1250,14 +1254,14 @@ export class Camera { public screenToWorld (out: Vec3, screenPos: Vec3): Vec3 { const width = this.width; const height = this.height; - const cx = this._orientedViewport.x * width; - const cy = this._orientedViewport.y * height; - const cw = this._orientedViewport.width * width; - const ch = this._orientedViewport.height * height; - const ySign = this._device.capabilities.clipSpaceSignY; - const preTransform = preTransforms[this._curTransform]; - - if (this._proj === CameraProjection.PERSPECTIVE) { + const cx = this._orientedViewport$.x * width; + const cy = this._orientedViewport$.y * height; + const cw = this._orientedViewport$.width * width; + const ch = this._orientedViewport$.height * height; + const ySign = this._device$.capabilities.clipSpaceSignY; + const preTransform = preTransforms[this._curTransform$]; + + if (this._proj$ === CameraProjection.PERSPECTIVE) { // calculate screen pos in far clip plane Vec3.set( out, @@ -1270,12 +1274,12 @@ export class Camera { const { x, y } = out; out.x = x * preTransform[0] + y * preTransform[2] * ySign; out.y = x * preTransform[1] + y * preTransform[3] * ySign; - Vec3.transformMat4(out, out, this._matViewProjInv); + Vec3.transformMat4(out, out, this._matViewProjInv$); // lerp to depth z - if (this._node) { this._node.getWorldPosition(v_a); } + if (this._node$) { this._node$.getWorldPosition(v_a); } - Vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z)); + Vec3.lerp(out, v_a, out, lerp(this._nearClip$ / this._farClip$, 1, screenPos.z)); } else { Vec3.set( out, @@ -1288,7 +1292,7 @@ export class Camera { const { x, y } = out; out.x = x * preTransform[0] + y * preTransform[2] * ySign; out.y = x * preTransform[1] + y * preTransform[3] * ySign; - Vec3.transformMat4(out, out, this._matViewProjInv); + Vec3.transformMat4(out, out, this._matViewProjInv$); } return out; @@ -1302,10 +1306,10 @@ export class Camera { * @returns the resulting vector */ public worldToScreen (out: Vec3, worldPos: Vec3 | Readonly): Vec3 { - const ySign = this._device.capabilities.clipSpaceSignY; - const preTransform = preTransforms[this._curTransform]; + const ySign = this._device$.capabilities.clipSpaceSignY; + const preTransform = preTransforms[this._curTransform$]; - Vec3.transformMat4(out, worldPos, this._matViewProj); + Vec3.transformMat4(out, worldPos, this._matViewProj$); const { x, y } = out; out.x = x * preTransform[0] + y * preTransform[2] * ySign; @@ -1313,10 +1317,10 @@ export class Camera { const width = this.width; const height = this.height; - const cx = this._orientedViewport.x * width; - const cy = this._orientedViewport.y * height; - const cw = this._orientedViewport.width * width; - const ch = this._orientedViewport.height * height; + const cx = this._orientedViewport$.x * width; + const cy = this._orientedViewport$.y * height; + const cw = this._orientedViewport$.width * width; + const ch = this._orientedViewport$.height * height; out.x = cx + (out.x + 1) * 0.5 * cw; out.y = cy + (out.y + 1) * 0.5 * ch; @@ -1335,8 +1339,8 @@ export class Camera { * @returns the resulting matrix */ public worldMatrixToScreen (out: Mat4, worldMatrix: Mat4, width: number, height: number): Mat4 { - Mat4.multiply(out, this._matViewProj, worldMatrix); - Mat4.multiply(out, correctionMatrices[this._curTransform], out); + Mat4.multiply(out, this._matViewProj$, worldMatrix); + Mat4.multiply(out, correctionMatrices[this._curTransform$], out); const halfWidth = width / 2; const halfHeight = height / 2; @@ -1356,22 +1360,22 @@ export class Camera { */ public calculateObliqueMat (viewSpacePlane: Vec4): void { const clipFar = new Vec4(Math.sign(viewSpacePlane.x), Math.sign(viewSpacePlane.y), 1.0, 1.0); - const viewFar = clipFar.transformMat4(this._matProjInv); + const viewFar = clipFar.transformMat4(this._matProjInv$); - const m4 = new Vec4(this._matProj.m03, this._matProj.m07, this._matProj.m11, this._matProj.m15); + const m4 = new Vec4(this._matProj$.m03, this._matProj$.m07, this._matProj$.m11, this._matProj$.m15); const scale = 2.0 / Vec4.dot(viewSpacePlane, viewFar); const newViewSpaceNearPlane = viewSpacePlane.multiplyScalar(scale); const m3 = newViewSpaceNearPlane.subtract(m4); - this._matProj.m02 = m3.x; - this._matProj.m06 = m3.y; - this._matProj.m10 = m3.z; - this._matProj.m14 = m3.w; + this._matProj$.m02 = m3.x; + this._matProj$.m06 = m3.y; + this._matProj$.m10 = m3.z; + this._matProj$.m14 = m3.w; } public getClipSpaceMinz (): number { - return this._device.capabilities.clipSpaceMinZ; + return this._device$.capabilities.clipSpaceMinZ; } /** @@ -1380,23 +1384,23 @@ export class Camera { * @param ev100 */ protected setExposure (ev100): void { - this._exposure = 0.833333 / (2.0 ** ev100); + this._exposure$ = 0.833333 / (2.0 ** ev100); } - private updateExposure (): void { - const ev100 = Math.log2((this._apertureValue * this._apertureValue) / this._shutterValue * 100.0 / this._isoValue); + private updateExposure$ (): void { + const ev100 = Math.log2((this._apertureValue$ * this._apertureValue$) / this._shutterValue$ * 100.0 / this._isoValue$); this.setExposure(ev100); } - private setDefaultUsage (): void { + private setDefaultUsage$ (): void { if (EDITOR) { if (cclegacy.GAME_VIEW) { - this._usage = CameraUsage.GAME_VIEW; + this._usage$ = CameraUsage.GAME_VIEW; } else { - this._usage = CameraUsage.EDITOR; + this._usage$ = CameraUsage.EDITOR; } } else { - this._usage = CameraUsage.GAME; + this._usage$ = CameraUsage.GAME; } } } diff --git a/cocos/render-scene/scene/light.ts b/cocos/render-scene/scene/light.ts index e3220a0094d..c7f678025a8 100644 --- a/cocos/render-scene/scene/light.ts +++ b/cocos/render-scene/scene/light.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { Vec3 } from '../../core'; +import { v3, Vec3 } from '../../core'; import { TransformBit } from '../../scene-graph/node-enum'; import { RenderScene } from '../core/render-scene'; import { Node } from '../../scene-graph'; @@ -93,7 +93,7 @@ export class Light { */ set color (color: Vec3) { this._color.set(color); - if (this._useColorTemperature) { Vec3.multiply(this._finalColor, this._color, this._colorTempRGB); } + if (this._useColorTemperature) { Vec3.multiply(this._finalColor$, this._color, this._colorTempRGB); } } get color (): Vec3 { @@ -106,7 +106,7 @@ export class Light { */ set useColorTemperature (enable: boolean) { this._useColorTemperature = enable; - if (enable) { Vec3.multiply(this._finalColor, this._color, this._colorTempRGB); } + if (enable) { Vec3.multiply(this._finalColor$, this._color, this._colorTempRGB); } } get useColorTemperature (): boolean { @@ -120,7 +120,7 @@ export class Light { set colorTemperature (val: number) { this._colorTemp = val; ColorTemperatureToRGB(this._colorTempRGB, this._colorTemp); - if (this._useColorTemperature) { Vec3.multiply(this._finalColor, this._color, this._colorTempRGB); } + if (this._useColorTemperature) { Vec3.multiply(this._finalColor$, this._color, this._colorTempRGB); } } get colorTemperature (): number { @@ -136,7 +136,7 @@ export class Light { } get finalColor (): Readonly { - return this._finalColor; + return this._finalColor$; } /** @@ -196,13 +196,13 @@ export class Light { protected _baked = false; - protected _color: Vec3 = new Vec3(1, 1, 1); + protected _color: Vec3 = v3(1, 1, 1); protected _colorTemp = 6550.0; - protected _colorTempRGB: Vec3 = new Vec3(1, 1, 1); + protected _colorTempRGB: Vec3 = v3(1, 1, 1); - private _finalColor: Vec3 = new Vec3(1, 1, 1); + private _finalColor$: Vec3 = v3(1, 1, 1); protected _scene: RenderScene | null = null; @@ -217,7 +217,7 @@ export class Light { protected _visibility = CAMERA_DEFAULT_MASK; public initialize (): void { - this.color = new Vec3(1, 1, 1); + this.color = v3(1, 1, 1); this.colorTemperature = 6550.0; } diff --git a/cocos/render-scene/scene/lod-group.ts b/cocos/render-scene/scene/lod-group.ts index 13786646feb..990caa0ab55 100644 --- a/cocos/render-scene/scene/lod-group.ts +++ b/cocos/render-scene/scene/lod-group.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ import { Model } from './model'; -import { Vec3, assertIsTrue } from '../../core'; +import { Vec3, assertIsTrue, v3 } from '../../core'; import { RenderScene } from '..'; import { Device, deviceManager } from '../../gfx'; import { Node } from '../../scene-graph'; @@ -35,25 +35,25 @@ export class LODData { // Range in [0, 1]. screenUsagePercentage = 1.0; - private _models: Model[] = []; + private _models$: Model[] = []; get models (): readonly Model[] { - return this._models; + return this._models$; } public addModel (model: Model): void { - this._models.splice(0, 0, model); + this._models$.splice(0, 0, model); } public eraseModel (model: Model): void { - const removeIndex = this._models.indexOf(model); + const removeIndex = this._models$.indexOf(model); if (removeIndex >= 0) { - this._models.splice(removeIndex, 1); + this._models$.splice(removeIndex, 1); } } public clearModels (): void { - this._models.length = 0; + this._models$.length = 0; } } @@ -69,7 +69,7 @@ export class LODGroup { public enabled = true; - private _localBoundaryCenter: Vec3 = new Vec3(0, 0, 0); + private _localBoundaryCenter$: Vec3 = v3(0, 0, 0); /** * @en Object Size in local space, may be auto-calculated value from object bounding box or value from user input. @@ -86,15 +86,15 @@ export class LODGroup { */ protected _lockedLODLevelVec: number[] = []; - private _isLockLevelChanged = false; + private _isLockLevelChanged$ = false; constructor () { this._device = deviceManager.gfxDevice; } - set localBoundaryCenter (val: Readonly) { this._localBoundaryCenter.set(val); } + set localBoundaryCenter (val: Readonly) { this._localBoundaryCenter$.set(val); } - get localBoundaryCenter (): Readonly { return this._localBoundaryCenter.clone(); } + get localBoundaryCenter (): Readonly { return this._localBoundaryCenter$.clone(); } get lodCount (): number { return this._lodDataArray.length; } @@ -115,13 +115,13 @@ export class LODGroup { lockLODLevels (lockLev: number[]): void { if (lockLev.length !== this._lockedLODLevelVec.length) { - this._isLockLevelChanged = true; + this._isLockLevelChanged$ = true; } else { const size = lockLev.length; let index = 0; for (; index < size; index++) { if (lockLev[index] !== this._lockedLODLevelVec[index]) { - this._isLockLevelChanged = true; + this._isLockLevelChanged$ = true; break; } } @@ -130,11 +130,11 @@ export class LODGroup { } isLockLevelChanged (): boolean { - return this._isLockLevelChanged; + return this._isLockLevelChanged$; } resetLockChangeFlag (): void { - this._isLockLevelChanged = false; + this._isLockLevelChanged$ = false; } getLockedLODLevels (): readonly number[] { @@ -189,10 +189,10 @@ export class LODGroup { distance = Vec3.len(this.localBoundaryCenter.transformMat4(this.node.worldMatrix).subtract(camera.node.worldPosition)); } - return this.distanceToScreenUsagePercentage(camera, distance, this.getWorldSpaceSize()); + return this.distanceToScreenUsagePercentage$(camera, distance, this.getWorldSpaceSize$()); } - private distanceToScreenUsagePercentage (camera: Camera, distance: number | undefined, size: number): number { + private distanceToScreenUsagePercentage$ (camera: Camera, distance: number | undefined, size: number): number { if (camera.projectionType === CameraProjection.PERSPECTIVE) { assertIsTrue(typeof distance === 'number', 'distance must be present for perspective projection'); return (size * camera.matProj.m05) / (distance * 2.0); // note: matProj.m11 is 1 / tan(fov / 2.0) @@ -201,7 +201,7 @@ export class LODGroup { } } - private getWorldSpaceSize (): number { + private getWorldSpaceSize$ (): number { const scale = this.node.scale; const maxScale = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)); return maxScale * this.objectSize; diff --git a/cocos/render-scene/scene/model.ts b/cocos/render-scene/scene/model.ts index 6591c3c920e..d5399825f23 100644 --- a/cocos/render-scene/scene/model.ts +++ b/cocos/render-scene/scene/model.ts @@ -33,11 +33,12 @@ import { RenderScene } from '../core/render-scene'; import { Texture2D } from '../../asset/assets/texture-2d'; import { SubModel } from './submodel'; import { IMacroPatch } from '../core/pass'; -import { Mat4, Vec3, Vec4, geometry, cclegacy, EPSILON } from '../../core'; +import { Mat4, Vec3, Vec4, geometry, cclegacy, EPSILON, v3, v4 } from '../../core'; import { Attribute, DescriptorSet, Device, Buffer, BufferInfo, BufferUsageBit, MemoryUsageBit, Filter, Address, SamplerInfo, deviceManager, Texture } from '../../gfx'; import { - UBOLocal, UBOSH, UBOWorldBound, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, + UBOLocal, + UBOLocalEnum, UBOSH, UBOSHEnum, UBOWorldBound, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, } from '../../rendering/define'; @@ -179,11 +180,11 @@ export class Model { * @zh 光照探针开关 */ get useLightProbe (): boolean { - return this._useLightProbe; + return this._useLightProbe$; } set useLightProbe (val) { - this._useLightProbe = val; + this._useLightProbe$ = val; this.onMacroPatchesStateChanged(); } @@ -192,11 +193,11 @@ export class Model { * @zh 模型所处的四面体索引 */ get tetrahedronIndex (): number { - return this._tetrahedronIndex; + return this._tetrahedronIndex$; } set tetrahedronIndex (index: number) { - this._tetrahedronIndex = index; + this._tetrahedronIndex$ = index; } /** @@ -470,7 +471,7 @@ export class Model { * @en Local ubo data * @zh 本地 ubo 数据 */ - protected _localData = new Float32Array(UBOLocal.COUNT); + protected _localData = new Float32Array(UBOLocalEnum.COUNT); /** * @en Local ubo buffer @@ -490,16 +491,16 @@ export class Model { */ protected _localSHBuffer: Buffer | null = null; - private _lightmap: Texture2D | null = null; - private _lightmapUVParam: Vec4 = new Vec4(); + private _lightmap$: Texture2D | null = null; + private _lightmapUVParam$: Vec4 = v4(); /** * @en located tetrahedron index * @zh 所处的四面体索引 */ - private _tetrahedronIndex = -1; - private _lastWorldBoundCenter = new Vec3(Infinity, Infinity, Infinity); - private _useLightProbe = false; + private _tetrahedronIndex$ = -1; + private _lastWorldBoundCenter$ = v3(Infinity, Infinity, Infinity); + private _useLightProbe$ = false; /** * @en World AABB buffer @@ -729,12 +730,12 @@ export class Model { } } if ((hasNonInstancingPass || forceUpdateUBO) && this._localBuffer) { - Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET); + Mat4.toArray(this._localData, worldMatrix, UBOLocalEnum.MAT_WORLD_OFFSET); Mat4.invert(m4_1, worldMatrix); Mat4.transpose(m4_1, m4_1); - Mat4.toArray(this._localData, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET); + Mat4.toArray(this._localData, m4_1, UBOLocalEnum.MAT_WORLD_IT_OFFSET); this._localBuffer.update(this._localData); } } @@ -749,11 +750,11 @@ export class Model { } public showTetrahedron (): boolean { - return this.isLightProbeAvailable(); + return this.isLightProbeAvailable$(); } - private isLightProbeAvailable (): boolean { - if (!this._useLightProbe) { + private isLightProbeAvailable$ (): boolean { + if (!this._useLightProbe$) { return false; } @@ -769,7 +770,7 @@ export class Model { return true; } - private updateSHBuffer (): void { + private updateSHBuffer$ (): void { if (!this._localSHData) { return; } @@ -800,11 +801,11 @@ export class Model { return; } - for (let i = 0; i < UBOSH.COUNT; i++) { + for (let i = 0; i < UBOSHEnum.COUNT; i++) { this._localSHData[i] = 0.0; } - this.updateSHBuffer(); + this.updateSHBuffer$(); } /** @@ -812,12 +813,12 @@ export class Model { * @zh 更新模型的球谐 ubo */ public updateSHUBOs (): void { - if (!this.isLightProbeAvailable()) { + if (!this.isLightProbeAvailable$()) { return; } const center = this._worldBounds!.center; - if (!EDITOR && center.equals(this._lastWorldBoundCenter, EPSILON)) { + if (!EDITOR && center.equals(this._lastWorldBoundCenter$, EPSILON)) { return; } @@ -825,9 +826,9 @@ export class Model { const weights = new Vec4(0.0, 0.0, 0.0, 0.0); const lightProbes = (cclegacy.director.root as Root).pipeline.pipelineSceneData.lightProbes; - this._lastWorldBoundCenter.set(center); - this._tetrahedronIndex = lightProbes.data!.getInterpolationWeights(center, this._tetrahedronIndex, weights); - const result = lightProbes.data!.getInterpolationSHCoefficients(this._tetrahedronIndex, weights, coefficients); + this._lastWorldBoundCenter$.set(center); + this._tetrahedronIndex$ = lightProbes.data!.getInterpolationWeights(center, this._tetrahedronIndex$, weights); + const result = lightProbes.data!.getInterpolationSHCoefficients(this._tetrahedronIndex$, weights, coefficients); if (!result) { return; } @@ -837,8 +838,8 @@ export class Model { } cclegacy.internal.SH.reduceRinging(coefficients, lightProbes.reduceRinging); - cclegacy.internal.SH.updateUBOData(this._localSHData, UBOSH.SH_LINEAR_CONST_R_OFFSET, coefficients); - this.updateSHBuffer(); + cclegacy.internal.SH.updateUBOData(this._localSHData, UBOSHEnum.SH_LINEAR_CONST_R_OFFSET, coefficients); + this.updateSHBuffer$(); } /** @@ -855,7 +856,7 @@ export class Model { this._worldBounds.copy(this._modelBounds); } - private _createSubModel (): SubModel { + private _createSubModel$ (): SubModel { return new SubModel(); } @@ -870,7 +871,7 @@ export class Model { this.initialize(); if (this._subModels[idx] == null) { - this._subModels[idx] = this._createSubModel(); + this._subModels[idx] = this._createSubModel$(); } else { this._subModels[idx].destroy(); } @@ -938,8 +939,8 @@ export class Model { * because the lighting map will influence the shader */ public initLightingmap (texture: Texture2D | null, uvParam: Vec4): void { - this._lightmap = texture; - this._lightmapUVParam = uvParam; + this._lightmap$ = texture; + this._lightmapUVParam$ = uvParam; } /** @@ -949,10 +950,10 @@ export class Model { * @param uvParam uv coordinate */ public updateLightingmap (texture: Texture2D | null, uvParam: Vec4): void { - Vec4.toArray(this._localData, uvParam, UBOLocal.LIGHTINGMAP_UVPARAM); + Vec4.toArray(this._localData, uvParam, UBOLocalEnum.LIGHTINGMAP_UVPARAM); this._localDataUpdated = true; - this._lightmap = texture; - this._lightmapUVParam = uvParam; + this._lightmap$ = texture; + this._lightmapUVParam$ = uvParam; this.onMacroPatchesStateChanged(); @@ -1094,8 +1095,8 @@ export class Model { */ public updateLocalShadowBias (): void { const sv = this._localData; - sv[UBOLocal.LOCAL_SHADOW_BIAS + 0] = this._shadowBias; - sv[UBOLocal.LOCAL_SHADOW_BIAS + 1] = this._shadowNormalBias; + sv[UBOLocalEnum.LOCAL_SHADOW_BIAS + 0] = this._shadowBias; + sv[UBOLocalEnum.LOCAL_SHADOW_BIAS + 1] = this._shadowNormalBias; this._localDataUpdated = true; } @@ -1105,8 +1106,8 @@ export class Model { */ public updateReflectionProbeId (): void { const sv = this._localData; - sv[UBOLocal.LOCAL_SHADOW_BIAS + 2] = this._reflectionProbeId; - sv[UBOLocal.LOCAL_SHADOW_BIAS + 3] = this._reflectionProbeBlendId; + sv[UBOLocalEnum.LOCAL_SHADOW_BIAS + 2] = this._reflectionProbeId; + sv[UBOLocalEnum.LOCAL_SHADOW_BIAS + 3] = this._reflectionProbeBlendId; let probe: ReflectionProbe | null = null; let blendProbe: ReflectionProbe | null = null; if (cclegacy.internal.reflectionProbeManager) { @@ -1115,45 +1116,45 @@ export class Model { } if (probe) { if (probe.probeType === ProbeType.PLANAR) { - sv[UBOLocal.REFLECTION_PROBE_DATA1] = probe.node.up.x; - sv[UBOLocal.REFLECTION_PROBE_DATA1 + 1] = probe.node.up.y; - sv[UBOLocal.REFLECTION_PROBE_DATA1 + 2] = probe.node.up.z; - sv[UBOLocal.REFLECTION_PROBE_DATA1 + 3] = 1.0; - - sv[UBOLocal.REFLECTION_PROBE_DATA2] = 1.0; - sv[UBOLocal.REFLECTION_PROBE_DATA2 + 1] = 0.0; - sv[UBOLocal.REFLECTION_PROBE_DATA2 + 2] = 0.0; - sv[UBOLocal.REFLECTION_PROBE_DATA2 + 3] = 1.0; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1] = probe.node.up.x; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1 + 1] = probe.node.up.y; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1 + 2] = probe.node.up.z; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1 + 3] = 1.0; + + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2] = 1.0; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2 + 1] = 0.0; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2 + 2] = 0.0; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2 + 3] = 1.0; } else { - sv[UBOLocal.REFLECTION_PROBE_DATA1] = probe.node.worldPosition.x; - sv[UBOLocal.REFLECTION_PROBE_DATA1 + 1] = probe.node.worldPosition.y; - sv[UBOLocal.REFLECTION_PROBE_DATA1 + 2] = probe.node.worldPosition.z; - sv[UBOLocal.REFLECTION_PROBE_DATA1 + 3] = 0.0; - - sv[UBOLocal.REFLECTION_PROBE_DATA2] = probe.size.x; - sv[UBOLocal.REFLECTION_PROBE_DATA2 + 1] = probe.size.y; - sv[UBOLocal.REFLECTION_PROBE_DATA2 + 2] = probe.size.z; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1] = probe.node.worldPosition.x; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1 + 1] = probe.node.worldPosition.y; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1 + 2] = probe.node.worldPosition.z; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA1 + 3] = 0.0; + + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2] = probe.size.x; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2 + 1] = probe.size.y; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2 + 2] = probe.size.z; const mipAndUseRGBE = probe.isRGBE() ? 1000 : 0; - sv[UBOLocal.REFLECTION_PROBE_DATA2 + 3] = probe.cubemap ? probe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE; + sv[UBOLocalEnum.REFLECTION_PROBE_DATA2 + 3] = probe.cubemap ? probe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE; } // eslint-disable-next-line max-len if (this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES || this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) { if (blendProbe) { - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1] = blendProbe.node.worldPosition.x; - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 1] = blendProbe.node.worldPosition.y; - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 2] = blendProbe.node.worldPosition.z; - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight; - - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2] = blendProbe.size.x; - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 1] = blendProbe.size.y; - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 2] = blendProbe.size.z; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA1] = blendProbe.node.worldPosition.x; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA1 + 1] = blendProbe.node.worldPosition.y; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA1 + 2] = blendProbe.node.worldPosition.z; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight; + + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA2] = blendProbe.size.x; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA2 + 1] = blendProbe.size.y; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA2 + 2] = blendProbe.size.z; const mipAndUseRGBE = blendProbe.isRGBE() ? 1000 : 0; // eslint-disable-next-line max-len - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 3] = blendProbe.cubemap ? blendProbe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA2 + 3] = blendProbe.cubemap ? blendProbe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE; } else if (this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) { //blend with skybox - sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight; + sv[UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight; } } } @@ -1167,7 +1168,7 @@ export class Model { */ public getMacroPatches (subModelIndex: number): IMacroPatch[] | null { let patches = this.receiveShadow ? shadowMapPatches : null; - if (this._lightmap != null) { + if (this._lightmap$ != null) { if (this.node && this.node.scene && !this.node.scene.globals.disableLightmap) { const mainLightIsStationary = this.node.scene.globals.bakedWithStationaryMainLight; const lightmapPathes = mainLightIsStationary ? stationaryLightMapPatches : staticLightMapPatches; @@ -1179,7 +1180,7 @@ export class Model { } } } - if (this._useLightProbe) { + if (this._useLightProbe$) { patches = patches ? patches.concat(lightProbePatches) : lightProbePatches; } const reflectionProbePatches: IMacroPatch[] = [ @@ -1237,27 +1238,27 @@ export class Model { this._localBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - UBOLocal.SIZE, - UBOLocal.SIZE, + UBOLocalEnum.SIZE, + UBOLocalEnum.SIZE, )); } } protected _initLocalSHDescriptors (subModelIndex: number): void { - if (!EDITOR && !this._useLightProbe) { + if (!EDITOR && !this._useLightProbe$) { return; } if (!this._localSHData) { - this._localSHData = new Float32Array(UBOSH.COUNT); + this._localSHData = new Float32Array(UBOSHEnum.COUNT); } if (!this._localSHBuffer) { this._localSHBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - UBOSH.SIZE, - UBOSH.SIZE, + UBOSHEnum.SIZE, + UBOSHEnum.SIZE, )); } } diff --git a/cocos/render-scene/scene/point-light.ts b/cocos/render-scene/scene/point-light.ts index 04e728431c2..8397d36420b 100644 --- a/cocos/render-scene/scene/point-light.ts +++ b/cocos/render-scene/scene/point-light.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { cclegacy, geometry, Vec3 } from '../../core'; +import { cclegacy, geometry, v3, Vec3 } from '../../core'; import { AABB } from '../../core/geometry'; import { Light, LightType, nt2lm } from './light'; @@ -45,13 +45,13 @@ export class PointLight extends Light { * @zh 点光源的光照范围。 */ set range (range: number) { - this._range = range; + this._range$ = range; - this._needUpdate = true; + this._needUpdate$ = true; } get range (): number { - return this._range; + return this._range$; } /** @@ -61,9 +61,9 @@ export class PointLight extends Light { get luminance (): number { const isHDR = cclegacy.director.root.pipeline.pipelineSceneData.isHDR; if (isHDR) { - return this._luminanceHDR; + return this._luminanceHDR$; } else { - return this._luminanceLDR; + return this._luminanceLDR$; } } set luminance (value: number) { @@ -80,10 +80,10 @@ export class PointLight extends Light { * @zh HDR 模式下光源的亮度。 */ get luminanceHDR (): number { - return this._luminanceHDR; + return this._luminanceHDR$; } set luminanceHDR (value: number) { - this._luminanceHDR = value; + this._luminanceHDR$ = value; } /** @@ -91,7 +91,7 @@ export class PointLight extends Light { * @zh LDR 模式下光源的亮度。 */ set luminanceLDR (value: number) { - this._luminanceLDR = value; + this._luminanceLDR$ = value; } /** @@ -102,11 +102,11 @@ export class PointLight extends Light { return this._aabb; } - private _needUpdate = false; - private _range = 1.0; - private _luminanceHDR = 0; - private _luminanceLDR = 0; - private _pos: Vec3 = new Vec3(); + private _needUpdate$ = false; + private _range$ = 1.0; + private _luminanceHDR$ = 0; + private _luminanceLDR$ = 0; + private _pos: Vec3 = v3(); private _aabb: AABB = AABB.create(); constructor () { @@ -127,11 +127,11 @@ export class PointLight extends Light { * @zh 更新光源影响范围。 */ public update (): void { - if (this._node && (this._node.hasChangedFlags || this._needUpdate)) { + if (this._node && (this._node.hasChangedFlags || this._needUpdate$)) { this._node.getWorldPosition(this._pos); - const range = this._range; + const range = this._range$; AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, range, range, range); - this._needUpdate = false; + this._needUpdate$ = false; } } } diff --git a/cocos/render-scene/scene/ranged-directional-light.ts b/cocos/render-scene/scene/ranged-directional-light.ts index 121e6fb7d37..9f51af263d6 100644 --- a/cocos/render-scene/scene/ranged-directional-light.ts +++ b/cocos/render-scene/scene/ranged-directional-light.ts @@ -36,8 +36,8 @@ export class RangedDirectionalLight extends Light { private _pos: Vec3 = new Vec3(0, 0, 0); private _scale: Vec3 = new Vec3(1, 1, 1); private _right: Vec3 = new Vec3(1, 0, 0); - private _illuminanceHDR: number = Ambient.SUN_ILLUM; - private _illuminanceLDR = 1.0; + private _illuminanceHDR$: number = Ambient.SUN_ILLUM; + private _illuminanceLDR$ = 1.0; /** * @en The direction vector of the light @@ -78,9 +78,9 @@ export class RangedDirectionalLight extends Light { get illuminance (): number { const isHDR = cclegacy.director.root.pipeline.pipelineSceneData.isHDR; if (isHDR) { - return this._illuminanceHDR; + return this._illuminanceHDR$; } else { - return this._illuminanceLDR; + return this._illuminanceLDR$; } } set illuminance (value: number) { @@ -97,10 +97,10 @@ export class RangedDirectionalLight extends Light { * @zh HDR 模式下光源的辐照度 */ get illuminanceHDR (): number { - return this._illuminanceHDR; + return this._illuminanceHDR$; } set illuminanceHDR (value: number) { - this._illuminanceHDR = value; + this._illuminanceHDR$ = value; } /** @@ -108,10 +108,10 @@ export class RangedDirectionalLight extends Light { * @zh LDR 模式下光源的辐照度 */ get illuminanceLDR (): number { - return this._illuminanceLDR; + return this._illuminanceLDR$; } set illuminanceLDR (value: number) { - this._illuminanceLDR = value; + this._illuminanceLDR$ = value; } constructor () { diff --git a/cocos/render-scene/scene/reflection-probe.ts b/cocos/render-scene/scene/reflection-probe.ts index c10d8548cc5..2bfb3deb4bc 100644 --- a/cocos/render-scene/scene/reflection-probe.ts +++ b/cocos/render-scene/scene/reflection-probe.ts @@ -22,16 +22,16 @@ THE SOFTWARE. */ import { EDITOR } from 'internal:constants'; -import { Camera, CameraAperture, CameraFOVAxis, CameraISO, CameraProjection, CameraShutter, CameraType, SKYBOX_FLAG, TrackingType } from './camera'; +import { Camera, CameraAperture, CameraFOVAxis, CameraISO, CameraProjection, CameraShutter, CameraType, SkyBoxFlagValue, TrackingType } from './camera'; import { Node } from '../../scene-graph/node'; -import { Color, Quat, Rect, toRadian, Vec2, Vec3, geometry, cclegacy, Vec4, Size } from '../../core'; +import { Color, Quat, Rect, toRadian, Vec2, Vec3, geometry, cclegacy, Vec4, Size, v3, quat } from '../../core'; import { CAMERA_DEFAULT_MASK } from '../../rendering/define'; import { ClearFlagBit, Framebuffer } from '../../gfx'; import { TextureCube } from '../../asset/assets/texture-cube'; import { RenderTexture } from '../../asset/assets/render-texture'; export enum ProbeClearFlag { - SKYBOX = SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL, + SKYBOX = SkyBoxFlagValue.VALUE | ClearFlagBit.DEPTH_STENCIL, SOLID_COLOR = ClearFlagBit.ALL, } @@ -68,50 +68,50 @@ export class ReflectionProbe { * @en Render cubemap's camera * @zh 渲染cubemap的相机 */ - private _camera: Camera | null = null; + private _camera$: Camera | null = null; /** * @en Unique id of probe. * @zh probe的唯一id */ - private _probeId = 0; + private _probeId$ = 0; - private _needRefresh = false; + private _needRefresh$ = false; - private _needRender = false; + private _needRender$ = false; - private _node: Node | null = null; + private _node$: Node | null = null; - private _cameraNode: Node | null = null; + private _cameraNode$: Node | null = null; /** * @en The AABB bounding box and probe only render the objects inside the bounding box. * @zh AABB包围盒,probe只渲染包围盒内的物体 */ - private _boundingBox: geometry.AABB | null = null; + private _boundingBox$: geometry.AABB | null = null; /** * @en The position of the camera in world space. * @zh 世界空间相机的位置 */ - private _cameraWorldPos = new Vec3(); + private _cameraWorldPos$ = v3(); /** * @en The rotation of the camera in world space. * @zh 世界空间相机的旋转 */ - private _cameraWorldRotation = new Quat(); + private _cameraWorldRotation$ = quat(); /** * @en The forward direction vertor of the camera in world space. * @zh 世界空间相机朝前的方向向量 */ - private _forward = new Vec3(); + private _forward$ = v3(); /** * @en The up direction vertor of the camera in world space. * @zh 世界空间相机朝上的方向向量 */ - private _up = new Vec3(); + private _up = v3(); /** * @en Reflection probe cube pattern preview sphere @@ -181,7 +181,7 @@ export class ReflectionProbe { } set visibility (val) { this._visibility = val; - this._camera!.visibility = this._visibility; + this._camera$!.visibility = this._visibility; } /** @@ -192,7 +192,7 @@ export class ReflectionProbe { this._size.set(value); const pos = this.node.getWorldPosition(); - geometry.AABB.set(this._boundingBox!, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); + geometry.AABB.set(this._boundingBox$!, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); } get size (): Vec3 { return this._size; @@ -211,11 +211,11 @@ export class ReflectionProbe { * @zh probe绑定的节点 */ get node (): Node { - return this._node!; + return this._node$!; } get camera (): Camera { - return this._camera!; + return this._camera$!; } /** @@ -223,29 +223,29 @@ export class ReflectionProbe { * @zh 刷新使用该probe的物体 */ set needRefresh (value: boolean) { - this._needRefresh = value; + this._needRefresh$ = value; } get needRefresh (): boolean { - return this._needRefresh; + return this._needRefresh$; } set needRender (value: boolean) { - this._needRender = value; + this._needRender$ = value; } get needRender (): boolean { - return this._needRender; + return this._needRender$; } get boundingBox (): geometry.AABB | null { - return this._boundingBox; + return this._boundingBox$; } set cameraNode (node: Node) { - this._cameraNode = node; + this._cameraNode$ = node; } get cameraNode (): Node { - return this._cameraNode!; + return this._cameraNode$!; } /** @@ -274,21 +274,21 @@ export class ReflectionProbe { } constructor (id: number) { - this._probeId = id; + this._probeId$ = id; } public initialize (node: Node, cameraNode: Node): void { - this._node = node; - this._cameraNode = cameraNode; + this._node$ = node; + this._cameraNode$ = cameraNode; const pos = this.node.getWorldPosition(); - this._boundingBox = geometry.AABB.create(pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); - this._createCamera(cameraNode); + this._boundingBox$ = geometry.AABB.create(pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); + this._createCamera$(cameraNode); } public initBakedTextures (): void { if (this.bakedCubeTextures.length === 0) { for (let i = 0; i < 6; i++) { - const renderTexture = this._createTargetTexture(this._resolution, this._resolution); + const renderTexture = this._createTargetTexture$(this._resolution, this._resolution); this.bakedCubeTextures.push(renderTexture); } } @@ -296,8 +296,8 @@ export class ReflectionProbe { public captureCubemap (): void { this.initBakedTextures(); - this._resetCameraParams(); - this._needRender = true; + this._resetCameraParams$(); + this._needRender$ = true; } /** @@ -309,28 +309,28 @@ export class ReflectionProbe { if (!sourceCamera) return; if (!this.realtimePlanarTexture) { const canvasSize = cclegacy.view.getDesignResolutionSize() as Size; - this.realtimePlanarTexture = this._createTargetTexture(canvasSize.width, canvasSize.height); + this.realtimePlanarTexture = this._createTargetTexture$(canvasSize.width, canvasSize.height); cclegacy.internal.reflectionProbeManager.updatePlanarMap(this, this.realtimePlanarTexture.getGFXTexture()); } - this._syncCameraParams(sourceCamera); - this._transformReflectionCamera(sourceCamera); - this._needRender = true; + this._syncCameraParams$(sourceCamera); + this._transformReflectionCamera$(sourceCamera); + this._needRender$ = true; } public switchProbeType (type: ProbeType, sourceCamera: Camera | null): void { if (type === ProbeType.CUBE) { - this._needRender = false; + this._needRender$ = false; } else if (sourceCamera !== null) { this.renderPlanarReflection(sourceCamera); } } public getProbeId (): number { - return this._probeId; + return this._probeId$; } public updateProbeId (id): void { - this._probeId = id; + this._probeId$ = id; } public renderArea (): Vec2 { @@ -350,9 +350,9 @@ export class ReflectionProbe { } public destroy (): void { - if (this._camera) { - this._camera.destroy(); - this._camera = null; + if (this._camera$) { + this._camera$.destroy(); + this._camera$ = null; } for (let i = 0; i < this.bakedCubeTextures.length; i++) { this.bakedCubeTextures[i].destroy(); @@ -379,7 +379,7 @@ export class ReflectionProbe { public updateBoundingBox (): void { if (this.node) { const pos = this.node.getWorldPosition(); - geometry.AABB.set(this._boundingBox!, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); + geometry.AABB.set(this._boundingBox$!, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z); } } @@ -406,7 +406,7 @@ export class ReflectionProbe { return true; } - private _syncCameraParams (camera: Camera): void { + private _syncCameraParams$ (camera: Camera): void { this.camera.projectionType = camera.projectionType; this.camera.orthoHeight = camera.orthoHeight; this.camera.nearClip = camera.nearClip; @@ -418,12 +418,12 @@ export class ReflectionProbe { this.camera.resize(camera.width, camera.height); } - private _createCamera (cameraNode: Node): Camera | null { + private _createCamera$ (cameraNode: Node): Camera | null { const root = cclegacy.director.root; - if (!this._camera) { - this._camera = root.createCamera(); - if (!this._camera) return null; - this._camera.initialize({ + if (!this._camera$) { + this._camera$ = root.createCamera(); + if (!this._camera$) return null; + this._camera$.initialize({ name: cameraNode.name, node: cameraNode, projection: CameraProjection.PERSPECTIVE, @@ -433,24 +433,24 @@ export class ReflectionProbe { trackingType: TrackingType.NO_TRACKING, }); } - this._camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1)); - this._camera.fovAxis = CameraFOVAxis.VERTICAL; - this._camera.fov = toRadian(90); - this._camera.orthoHeight = 10; - this._camera.nearClip = 1; - this._camera.farClip = 1000; - this._camera.clearColor = this._backgroundColor; - this._camera.clearDepth = 1.0; - this._camera.clearStencil = 0.0; - this._camera.clearFlag = this._clearFlag; - this._camera.visibility = this._visibility; - this._camera.aperture = CameraAperture.F16_0; - this._camera.shutter = CameraShutter.D125; - this._camera.iso = CameraISO.ISO100; - return this._camera; - } - - private _resetCameraParams (): void { + this._camera$.setViewportInOrientedSpace(new Rect(0, 0, 1, 1)); + this._camera$.fovAxis = CameraFOVAxis.VERTICAL; + this._camera$.fov = toRadian(90); + this._camera$.orthoHeight = 10; + this._camera$.nearClip = 1; + this._camera$.farClip = 1000; + this._camera$.clearColor = this._backgroundColor; + this._camera$.clearDepth = 1.0; + this._camera$.clearStencil = 0.0; + this._camera$.clearFlag = this._clearFlag; + this._camera$.visibility = this._visibility; + this._camera$.aperture = CameraAperture.F16_0; + this._camera$.shutter = CameraShutter.D125; + this._camera$.iso = CameraISO.ISO100; + return this._camera$; + } + + private _resetCameraParams$ (): void { this.camera.projectionType = CameraProjection.PERSPECTIVE; this.camera.orthoHeight = 10; this.camera.nearClip = 1; @@ -468,29 +468,29 @@ export class ReflectionProbe { this.camera.update(true); } - private _createTargetTexture (width: number, height: number): RenderTexture { + private _createTargetTexture$ (width: number, height: number): RenderTexture { const rt = new RenderTexture(); rt.reset({ width, height }); return rt; } - private _transformReflectionCamera (sourceCamera: Camera): void { + private _transformReflectionCamera$ (sourceCamera: Camera): void { const offset = Vec3.dot(this.node.worldPosition, this.node.up); - this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset); - this.cameraNode.worldPosition = this._cameraWorldPos; + this._reflect$(this._cameraWorldPos$, sourceCamera.node.worldPosition, this.node.up, offset); + this.cameraNode.worldPosition = this._cameraWorldPos$; - Vec3.transformQuat(this._forward, Vec3.FORWARD, sourceCamera.node.worldRotation); - this._reflect(this._forward, this._forward, this.node.up, 0); - this._forward.normalize(); - this._forward.negative(); + Vec3.transformQuat(this._forward$, Vec3.FORWARD, sourceCamera.node.worldRotation); + this._reflect$(this._forward$, this._forward$, this.node.up, 0); + this._forward$.normalize(); + this._forward$.negative(); Vec3.transformQuat(this._up, Vec3.UP, sourceCamera.node.worldRotation); - this._reflect(this._up, this._up, this.node.up, 0); + this._reflect$(this._up, this._up, this.node.up, 0); this._up.normalize(); - Quat.fromViewUp(this._cameraWorldRotation, this._forward, this._up); + Quat.fromViewUp(this._cameraWorldRotation$, this._forward$, this._up); - this.cameraNode.worldRotation = this._cameraWorldRotation; + this.cameraNode.worldRotation = this._cameraWorldRotation$; this.camera.update(true); @@ -500,7 +500,7 @@ export class ReflectionProbe { this.camera.calculateObliqueMat(viewSpaceProbe); } - private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 { + private _reflect$ (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 { const n = Vec3.clone(normal); n.normalize(); const dist = Vec3.dot(n, point) - offset; diff --git a/cocos/render-scene/scene/skybox.ts b/cocos/render-scene/scene/skybox.ts index 30ce5bb5960..7e148c6ef98 100644 --- a/cocos/render-scene/scene/skybox.ts +++ b/cocos/render-scene/scene/skybox.ts @@ -38,7 +38,7 @@ import { Enum, cclegacy } from '../../core'; let skybox_mesh: Mesh | null = null; let skybox_material: Material | null = null; -export const EnvironmentLightingType = Enum({ +export enum EnvironmentLightingType { /** * @zh * 半球漫反射 @@ -46,7 +46,7 @@ export const EnvironmentLightingType = Enum({ * hemisphere diffuse * @readonly */ - HEMISPHERE_DIFFUSE: 0, + HEMISPHERE_DIFFUSE = 0, /** * @zh * 半球漫反射和环境反射 @@ -54,7 +54,7 @@ export const EnvironmentLightingType = Enum({ * hemisphere diffuse and Environment reflection * @readonly */ - AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION: 1, + AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION = 1, /** * @zh * 漫反射卷积图和环境反射 @@ -62,8 +62,9 @@ export const EnvironmentLightingType = Enum({ * diffuse convolution map and environment reflection * @readonly */ - DIFFUSEMAP_WITH_REFLECTION: 2, -}); + DIFFUSEMAP_WITH_REFLECTION = 2, +} +Enum(EnvironmentLightingType); /** * @en The skybox configuration of the render scene, diff --git a/cocos/render-scene/scene/submodel.ts b/cocos/render-scene/scene/submodel.ts index 041c1b7060a..ac06ec9bfc4 100644 --- a/cocos/render-scene/scene/submodel.ts +++ b/cocos/render-scene/scene/submodel.ts @@ -24,7 +24,8 @@ import { RenderingSubMesh } from '../../asset/assets/rendering-sub-mesh'; import { RenderPriority, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_STORAGE_BINDING, - INST_MAT_WORLD, INST_SH, UBOSH, isEnableEffect } from '../../rendering/define'; + INST_MAT_WORLD, INST_SH, isEnableEffect, + UBOSHEnum } from '../../rendering/define'; import { BatchingSchemes, IMacroPatch, Pass } from '../core/pass'; import { DescriptorSet, DescriptorSetInfo, Device, InputAssembler, Texture, TextureType, TextureUsageBit, TextureInfo, Format, Sampler, Filter, Address, Shader, SamplerInfo, deviceManager, @@ -324,7 +325,6 @@ export class SubModel { * @zh 管线更新回调 */ public onPipelineStateChanged (): void { - const passes = this._passes; if (!passes) { return; } @@ -439,7 +439,7 @@ export class SubModel { */ public updateInstancedSH (data: Float32Array, idx: number): void { const attrs = this.instancedAttributeBlock.views; - const count = (UBOSH.SH_QUADRATIC_R_OFFSET - UBOSH.SH_LINEAR_CONST_R_OFFSET) / 4; + const count = (UBOSHEnum.SH_QUADRATIC_R_OFFSET - UBOSHEnum.SH_LINEAR_CONST_R_OFFSET) / 4; let offset = 0; for (let i = idx; i < idx + count; i++) { diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 7b0db79fcdd..648946d75a7 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -29,7 +29,7 @@ import { BufferInfo, Buffer, BufferUsageBit, ClearFlagBit, Color, DescriptorSet, Device, } from '../../gfx'; import { ReflectionProbe } from '../../render-scene/scene/reflection-probe'; -import { Camera, SKYBOX_FLAG } from '../../render-scene/scene/camera'; +import { Camera, SkyBoxFlagValue } from '../../render-scene/scene/camera'; import { CSMLevel, ShadowType, Shadows } from '../../render-scene/scene/shadows'; import { Light, LightType } from '../../render-scene/scene/light'; import { DirectionalLight } from '../../render-scene/scene/directional-light'; @@ -37,7 +37,7 @@ import { RangedDirectionalLight } from '../../render-scene/scene/ranged-directio import { PointLight } from '../../render-scene/scene/point-light'; import { SphereLight } from '../../render-scene/scene/sphere-light'; import { SpotLight } from '../../render-scene/scene/spot-light'; -import { UBOForwardLight, supportsR32FloatTexture, supportsRGBA16HalfFloatTexture } from '../define'; +import { UBOForwardLightEnum, supportsR32FloatTexture, supportsRGBA16HalfFloatTexture } from '../define'; import { BasicPipeline } from './pipeline'; import { AttachmentType, LightInfo, @@ -133,7 +133,7 @@ export function getLoadOpOfClearFlag (clearFlag: ClearFlagBit, attachment: Attac let loadOp = LoadOp.CLEAR; if (!(clearFlag & ClearFlagBit.COLOR) && attachment === AttachmentType.RENDER_TARGET) { - if (clearFlag & SKYBOX_FLAG) { + if (clearFlag & SkyBoxFlagValue.VALUE) { loadOp = LoadOp.CLEAR; } else { loadOp = LoadOp.LOAD; @@ -765,14 +765,14 @@ export function SetLightUBO ( luminanceLDR = rangedDirLight.illuminanceLDR; } - let index = offset + UBOForwardLight.LIGHT_POS_OFFSET; + let index = offset + UBOForwardLightEnum.LIGHT_POS_OFFSET; buffer.set(vec4Array, index); - index = offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET; + index = offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET; vec4Array.set([size, range, 0, 0]); buffer.set(vec4Array, index); - index = offset + UBOForwardLight.LIGHT_COLOR_OFFSET; + index = offset + UBOForwardLightEnum.LIGHT_COLOR_OFFSET; const color = light ? light.color : new Color(); if (light && light.useColorTemperature) { const tempRGB = light.colorTemperatureRGB; @@ -793,50 +793,50 @@ export function SetLightUBO ( switch (light ? light.type : LightType.UNKNOWN) { case LightType.SPHERE: - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0; break; case LightType.SPOT: { const spotLight = light as SpotLight; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = spotLight.spotAngle; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = (shadowInfo && shadowInfo.enabled + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = spotLight.spotAngle; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = (shadowInfo && shadowInfo.enabled && spotLight.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap) ? 1.0 : 0.0; - index = offset + UBOForwardLight.LIGHT_DIR_OFFSET; + index = offset + UBOForwardLightEnum.LIGHT_DIR_OFFSET; const direction = spotLight.direction; buffer[index++] = direction.x; buffer[index++] = direction.y; buffer[index] = direction.z; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 0] = 0; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 1] = 0; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 2] = 0; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 3] = spotLight.angleAttenuationStrength; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 0] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 1] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 2] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 3] = spotLight.angleAttenuationStrength; } break; case LightType.POINT: - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0; break; case LightType.RANGED_DIRECTIONAL: { const rangedDirLight = light as RangedDirectionalLight; const right = rangedDirLight.right; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 0] = right.x; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 1] = right.y; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = right.z; - buffer[offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 0] = right.x; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 1] = right.y; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 2] = right.z; + buffer[offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET + 3] = 0; const direction = rangedDirLight.direction; - buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 0] = direction.x; - buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 1] = direction.y; - buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 2] = direction.z; - buffer[offset + UBOForwardLight.LIGHT_DIR_OFFSET + 3] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_DIR_OFFSET + 0] = direction.x; + buffer[offset + UBOForwardLightEnum.LIGHT_DIR_OFFSET + 1] = direction.y; + buffer[offset + UBOForwardLightEnum.LIGHT_DIR_OFFSET + 2] = direction.z; + buffer[offset + UBOForwardLightEnum.LIGHT_DIR_OFFSET + 3] = 0; const scale = rangedDirLight.scale; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 0] = scale.x * 0.5; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 1] = scale.y * 0.5; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 2] = scale.z * 0.5; - buffer[offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + 3] = 0; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 0] = scale.x * 0.5; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 1] = scale.y * 0.5; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 2] = scale.z * 0.5; + buffer[offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET + 3] = 0; } break; default: break; diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 4c17d8ba0fe..3e643036033 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -77,7 +77,7 @@ import { Vec4 } from '../../core/math/vec4'; import { Camera } from '../../render-scene/scene/camera'; import { ShadowType } from '../../render-scene/scene/shadows'; import { Root } from '../../root'; -import { IRenderPass, SetIndex, UBODeferredLight, UBOForwardLight, UBOLocal } from '../define'; +import { IRenderPass, SetIndex, UBODeferredLight, UBOForwardLight, UBOLocal, UBOLocalEnum } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; import { PipelineInputAssemblerData } from '../render-types'; import { DescriptorSetData, LayoutGraphData, LayoutGraphDataValue, PipelineLayoutData, RenderPhaseData, RenderStageData } from './layout-graph'; @@ -1443,8 +1443,8 @@ class BlitInfo { this._localUBO = context.device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - UBOLocal.SIZE, - UBOLocal.SIZE, + UBOLocalEnum.SIZE, + UBOLocalEnum.SIZE, )); } diff --git a/cocos/rendering/custom/layout-graph-utils.ts b/cocos/rendering/custom/layout-graph-utils.ts index 43b709107bd..b152c07107a 100644 --- a/cocos/rendering/custom/layout-graph-utils.ts +++ b/cocos/rendering/custom/layout-graph-utils.ts @@ -28,7 +28,7 @@ import { DescriptorBlockData, DescriptorData, DescriptorSetLayoutData, LayoutGra import { EffectAsset } from '../../asset/assets'; import { assert, error, warn } from '../../core'; import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, Feature, Format, FormatFeatureBit, GetTypeSize, PipelineLayout, PipelineLayoutInfo, ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; -import { UBOForwardLight, UBOSkinning } from '../define'; +import { UBOForwardLight, UBOForwardLightEnum, UBOSkinning } from '../define'; import { UpdateFrequency, DescriptorBlockIndex, DescriptorTypeOrder, ParameterType } from './types'; export const INVALID_ID = 0xFFFFFFFF; @@ -111,11 +111,11 @@ export function getCustomPhaseID (lg: LayoutGraphData, subpassOrPassID: number, } export const DEFAULT_UNIFORM_COUNTS: Map = new Map([ - ['cc_lightPos', UBOForwardLight.LIGHTS_PER_PASS], - ['cc_lightColor', UBOForwardLight.LIGHTS_PER_PASS], - ['cc_lightSizeRangeAngle', UBOForwardLight.LIGHTS_PER_PASS], - ['cc_lightDir', UBOForwardLight.LIGHTS_PER_PASS], - ['cc_lightBoundingSizeVS', UBOForwardLight.LIGHTS_PER_PASS], + ['cc_lightPos', UBOForwardLightEnum.LIGHTS_PER_PASS], + ['cc_lightColor', UBOForwardLightEnum.LIGHTS_PER_PASS], + ['cc_lightSizeRangeAngle', UBOForwardLightEnum.LIGHTS_PER_PASS], + ['cc_lightDir', UBOForwardLightEnum.LIGHTS_PER_PASS], + ['cc_lightBoundingSizeVS', UBOForwardLightEnum.LIGHTS_PER_PASS], ]); export const DYNAMIC_UNIFORM_BLOCK: Set = new Set([ diff --git a/cocos/rendering/custom/scene-culling.ts b/cocos/rendering/custom/scene-culling.ts index e7e333d4e4c..2f64e196f3e 100644 --- a/cocos/rendering/custom/scene-culling.ts +++ b/cocos/rendering/custom/scene-culling.ts @@ -5,7 +5,7 @@ import { CommandBuffer, Device, Buffer, BufferInfo, BufferViewInfo, MemoryUsageB import { BatchingSchemes, RenderScene } from '../../render-scene'; import { CSMLevel, Camera, DirectionalLight, Light, LightType, Model, PointLight, ProbeType, RangedDirectionalLight, - ReflectionProbe, SKYBOX_FLAG, ShadowType, Shadows, SphereLight, SpotLight } from '../../render-scene/scene'; + ReflectionProbe, SkyBoxFlagValue, ShadowType, Shadows, SphereLight, SpotLight } from '../../render-scene/scene'; import { Layers, Node } from '../../scene-graph'; import { PipelineSceneData } from '../pipeline-scene-data'; import { bool, AlignUp, SetLightUBO, hashCombineKey } from './define'; @@ -174,7 +174,7 @@ function sceneCulling ( const skybox = pSceneData.skybox; const skyboxModel = skybox.model; const visibility = camera.visibility; - const camSkyboxFlag = camera.clearFlag & SKYBOX_FLAG; + const camSkyboxFlag = camera.clearFlag & SkyBoxFlagValue.VALUE; if (!castShadow && skybox && skybox.enabled && skyboxModel && camSkyboxFlag) { models.push(skyboxModel); } @@ -512,7 +512,7 @@ export class SceneCulling { return camera.frustum; } if (shadows.enabled && shadows.type === ShadowType.ShadowMap && mainLight && mainLight.node) { - // pplSceneData.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); + // pplSceneData.updateShadowUBORange(UBOShadowEnum.SHADOW_COLOR_OFFSET, shadows.shadowColor); csmLayers.update(pplSceneData, camera); } diff --git a/cocos/rendering/deferred/deferred-pipeline-scene-data.ts b/cocos/rendering/deferred/deferred-pipeline-scene-data.ts index 793eec5fe09..6d68cd34a7b 100644 --- a/cocos/rendering/deferred/deferred-pipeline-scene-data.ts +++ b/cocos/rendering/deferred/deferred-pipeline-scene-data.ts @@ -30,7 +30,7 @@ import { macro } from '../../core/platform/macro'; import { legacyCC } from '../../core/global-exports'; // Anti-aliasing type, other types will be gradually added in the future -export enum AntiAliasing { +export enum DeferredAntiAliasing { NONE, FXAA, } @@ -39,12 +39,12 @@ export const BLOOM_DOWNSAMPLEPASS_INDEX = 1; export const BLOOM_UPSAMPLEPASS_INDEX = BLOOM_DOWNSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM; export const BLOOM_COMBINEPASS_INDEX = BLOOM_UPSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM; export class DeferredPipelineSceneData extends PipelineSceneData { - protected _antiAliasing: AntiAliasing = AntiAliasing.NONE; + protected _antiAliasing: DeferredAntiAliasing = DeferredAntiAliasing.NONE; constructor () { super(); } - set antiAliasing (value: AntiAliasing) { + set antiAliasing (value: DeferredAntiAliasing) { this._antiAliasing = value; if (this._postprocessMaterial) { const defines = this._postprocessMaterial.passes[0].defines; @@ -61,7 +61,7 @@ export class DeferredPipelineSceneData extends PipelineSceneData { } } - get antiAliasing (): AntiAliasing { + get antiAliasing (): DeferredAntiAliasing { return this._antiAliasing; } diff --git a/cocos/rendering/deferred/lighting-stage.ts b/cocos/rendering/deferred/lighting-stage.ts index e3900982689..aa7d778b25a 100644 --- a/cocos/rendering/deferred/lighting-stage.ts +++ b/cocos/rendering/deferred/lighting-stage.ts @@ -30,7 +30,7 @@ import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { Camera } from '../../render-scene/scene/camera'; import { LightType } from '../../render-scene/scene/light'; -import { UBODeferredLight, SetIndex, UBOForwardLight, UBOLocal } from '../define'; +import { UBODeferredLight, SetIndex, UBOForwardLight, UBOLocal, UBOLocalEnum } from '../define'; import { getPhaseID } from '../pass-phase'; import { Color, Rect, Buffer, BufferUsageBit, MemoryUsageBit, BufferInfo, BufferViewInfo, DescriptorSet, DescriptorSetLayout, DescriptorSetInfo, PipelineState, ClearFlagBit } from '../../gfx'; @@ -286,8 +286,8 @@ export class LightingStage extends RenderStage { const _localUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - UBOLocal.SIZE, - UBOLocal.SIZE, + UBOLocalEnum.SIZE, + UBOLocalEnum.SIZE, )); this._descriptorSet.bindBuffer(UBOLocal.BINDING, _localUBO); } diff --git a/cocos/rendering/deferred/postprocess-stage.ts b/cocos/rendering/deferred/postprocess-stage.ts index c1a6babefa6..2f9fab463b6 100644 --- a/cocos/rendering/deferred/postprocess-stage.ts +++ b/cocos/rendering/deferred/postprocess-stage.ts @@ -28,7 +28,7 @@ */ import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { Camera } from '../../render-scene/scene'; -import { SetIndex, UBOLocal } from '../define'; +import { SetIndex, UBOLocal, UBOLocalEnum } from '../define'; import { Color, Rect, PipelineState, ClearFlagBit, DescriptorSetInfo, BufferInfo, BufferUsageBit, MemoryUsageBit } from '../../gfx'; import { IRenderStageInfo, RenderStage } from '../render-stage'; import { CommonStagePriority } from '../enum'; @@ -146,8 +146,8 @@ export class PostProcessStage extends RenderStage { this._localUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, - UBOLocal.SIZE, - UBOLocal.SIZE, + UBOLocalEnum.SIZE, + UBOLocalEnum.SIZE, )); this._stageDesc.bindBuffer(UBOLocal.BINDING, this._localUBO); } diff --git a/cocos/rendering/define.ts b/cocos/rendering/define.ts index 4d0a99487fd..7fad102c0c7 100644 --- a/cocos/rendering/define.ts +++ b/cocos/rendering/define.ts @@ -179,20 +179,32 @@ export const bindingMappingInfo = new BindingMappingInfo( [0, 2, 1, 3], // Set Order Indices ); +export enum UBOGlobalEnum { + TIME_OFFSET = 0, + SCREEN_SIZE_OFFSET = TIME_OFFSET + 4, + NATIVE_SIZE_OFFSET = SCREEN_SIZE_OFFSET + 4, + PROBE_INFO_OFFSET = NATIVE_SIZE_OFFSET + 4, + + DEBUG_VIEW_MODE_OFFSET = PROBE_INFO_OFFSET + 4, + + COUNT = DEBUG_VIEW_MODE_OFFSET + 4, + SIZE = COUNT * 4, +} + /** * @en The global uniform buffer object * @zh 全局 UBO。 */ export class UBOGlobal { - public static readonly TIME_OFFSET = 0; - public static readonly SCREEN_SIZE_OFFSET = UBOGlobal.TIME_OFFSET + 4; - public static readonly NATIVE_SIZE_OFFSET = UBOGlobal.SCREEN_SIZE_OFFSET + 4; - public static readonly PROBE_INFO_OFFSET = UBOGlobal.NATIVE_SIZE_OFFSET + 4; + public static readonly TIME_OFFSET = UBOGlobalEnum.TIME_OFFSET; + public static readonly SCREEN_SIZE_OFFSET = UBOGlobalEnum.SCREEN_SIZE_OFFSET; + public static readonly NATIVE_SIZE_OFFSET = UBOGlobalEnum.NATIVE_SIZE_OFFSET; + public static readonly PROBE_INFO_OFFSET = UBOGlobalEnum.PROBE_INFO_OFFSET; - public static readonly DEBUG_VIEW_MODE_OFFSET = UBOGlobal.PROBE_INFO_OFFSET + 4; + public static readonly DEBUG_VIEW_MODE_OFFSET = UBOGlobalEnum.DEBUG_VIEW_MODE_OFFSET; - public static readonly COUNT = UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 4; - public static readonly SIZE = UBOGlobal.COUNT * 4; + public static readonly COUNT = UBOGlobalEnum.COUNT; + public static readonly SIZE = UBOGlobalEnum.SIZE; public static readonly NAME = 'CCGlobal'; public static readonly BINDING = PipelineGlobalBindings.UBO_GLOBAL; @@ -209,32 +221,56 @@ export class UBOGlobal { globalDescriptorSetLayout.layouts[UBOGlobal.NAME] = UBOGlobal.LAYOUT; globalDescriptorSetLayout.bindings[UBOGlobal.BINDING] = UBOGlobal.DESCRIPTOR; +export enum UBOCameraEnum { + MAT_VIEW_OFFSET = 0, + MAT_VIEW_INV_OFFSET = MAT_VIEW_OFFSET + 16, + MAT_PROJ_OFFSET = MAT_VIEW_INV_OFFSET + 16, + MAT_PROJ_INV_OFFSET = MAT_PROJ_OFFSET + 16, + MAT_VIEW_PROJ_OFFSET = MAT_PROJ_INV_OFFSET + 16, + MAT_VIEW_PROJ_INV_OFFSET = MAT_VIEW_PROJ_OFFSET + 16, + CAMERA_POS_OFFSET = MAT_VIEW_PROJ_INV_OFFSET + 16, + SURFACE_TRANSFORM_OFFSET = CAMERA_POS_OFFSET + 4, + SCREEN_SCALE_OFFSET = SURFACE_TRANSFORM_OFFSET + 4, + EXPOSURE_OFFSET = SCREEN_SCALE_OFFSET + 4, + MAIN_LIT_DIR_OFFSET = EXPOSURE_OFFSET + 4, + MAIN_LIT_COLOR_OFFSET = MAIN_LIT_DIR_OFFSET + 4, + AMBIENT_SKY_OFFSET = MAIN_LIT_COLOR_OFFSET + 4, + AMBIENT_GROUND_OFFSET = AMBIENT_SKY_OFFSET + 4, + GLOBAL_FOG_COLOR_OFFSET = AMBIENT_GROUND_OFFSET + 4, + GLOBAL_FOG_BASE_OFFSET = GLOBAL_FOG_COLOR_OFFSET + 4, + GLOBAL_FOG_ADD_OFFSET = GLOBAL_FOG_BASE_OFFSET + 4, + NEAR_FAR_OFFSET = GLOBAL_FOG_ADD_OFFSET + 4, + VIEW_PORT_OFFSET = NEAR_FAR_OFFSET + 4, + COUNT = VIEW_PORT_OFFSET + 4, + SIZE = COUNT * 4, +} + /** * @en The global camera uniform buffer object * @zh 全局相机 UBO。 */ export class UBOCamera { - public static readonly MAT_VIEW_OFFSET = 0; - public static readonly MAT_VIEW_INV_OFFSET = UBOCamera.MAT_VIEW_OFFSET + 16; - public static readonly MAT_PROJ_OFFSET = UBOCamera.MAT_VIEW_INV_OFFSET + 16; - public static readonly MAT_PROJ_INV_OFFSET = UBOCamera.MAT_PROJ_OFFSET + 16; - public static readonly MAT_VIEW_PROJ_OFFSET = UBOCamera.MAT_PROJ_INV_OFFSET + 16; - public static readonly MAT_VIEW_PROJ_INV_OFFSET = UBOCamera.MAT_VIEW_PROJ_OFFSET + 16; - public static readonly CAMERA_POS_OFFSET = UBOCamera.MAT_VIEW_PROJ_INV_OFFSET + 16; - public static readonly SURFACE_TRANSFORM_OFFSET = UBOCamera.CAMERA_POS_OFFSET + 4; - public static readonly SCREEN_SCALE_OFFSET = UBOCamera.SURFACE_TRANSFORM_OFFSET + 4; - public static readonly EXPOSURE_OFFSET = UBOCamera.SCREEN_SCALE_OFFSET + 4; - public static readonly MAIN_LIT_DIR_OFFSET = UBOCamera.EXPOSURE_OFFSET + 4; - public static readonly MAIN_LIT_COLOR_OFFSET = UBOCamera.MAIN_LIT_DIR_OFFSET + 4; - public static readonly AMBIENT_SKY_OFFSET = UBOCamera.MAIN_LIT_COLOR_OFFSET + 4; - public static readonly AMBIENT_GROUND_OFFSET = UBOCamera.AMBIENT_SKY_OFFSET + 4; - public static readonly GLOBAL_FOG_COLOR_OFFSET = UBOCamera.AMBIENT_GROUND_OFFSET + 4; - public static readonly GLOBAL_FOG_BASE_OFFSET = UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 4; - public static readonly GLOBAL_FOG_ADD_OFFSET = UBOCamera.GLOBAL_FOG_BASE_OFFSET + 4; - public static readonly NEAR_FAR_OFFSET = UBOCamera.GLOBAL_FOG_ADD_OFFSET + 4; - public static readonly VIEW_PORT_OFFSET = UBOCamera.NEAR_FAR_OFFSET + 4; - public static readonly COUNT = UBOCamera.VIEW_PORT_OFFSET + 4; - public static readonly SIZE = UBOCamera.COUNT * 4; + public static readonly MAT_VIEW_OFFSET = UBOCameraEnum.MAT_VIEW_OFFSET; + public static readonly MAT_VIEW_INV_OFFSET = UBOCameraEnum.MAT_VIEW_INV_OFFSET; + public static readonly MAT_PROJ_OFFSET = UBOCameraEnum.MAT_PROJ_OFFSET; + public static readonly MAT_PROJ_INV_OFFSET = UBOCameraEnum.MAT_PROJ_INV_OFFSET; + public static readonly MAT_VIEW_PROJ_OFFSET = UBOCameraEnum.MAT_VIEW_PROJ_OFFSET; + public static readonly MAT_VIEW_PROJ_INV_OFFSET = UBOCameraEnum.MAT_VIEW_PROJ_INV_OFFSET; + public static readonly CAMERA_POS_OFFSET = UBOCameraEnum.CAMERA_POS_OFFSET; + public static readonly SURFACE_TRANSFORM_OFFSET = UBOCameraEnum.SURFACE_TRANSFORM_OFFSET; + public static readonly SCREEN_SCALE_OFFSET = UBOCameraEnum.SCREEN_SCALE_OFFSET; + public static readonly EXPOSURE_OFFSET = UBOCameraEnum.EXPOSURE_OFFSET; + public static readonly MAIN_LIT_DIR_OFFSET = UBOCameraEnum.MAIN_LIT_DIR_OFFSET; + public static readonly MAIN_LIT_COLOR_OFFSET = UBOCameraEnum.MAIN_LIT_COLOR_OFFSET; + public static readonly AMBIENT_SKY_OFFSET = UBOCameraEnum.AMBIENT_SKY_OFFSET; + public static readonly AMBIENT_GROUND_OFFSET = UBOCameraEnum.AMBIENT_GROUND_OFFSET; + public static readonly GLOBAL_FOG_COLOR_OFFSET = UBOCameraEnum.GLOBAL_FOG_COLOR_OFFSET; + public static readonly GLOBAL_FOG_BASE_OFFSET = UBOCameraEnum.GLOBAL_FOG_BASE_OFFSET; + public static readonly GLOBAL_FOG_ADD_OFFSET = UBOCameraEnum.GLOBAL_FOG_ADD_OFFSET; + public static readonly NEAR_FAR_OFFSET = UBOCameraEnum.NEAR_FAR_OFFSET; + public static readonly VIEW_PORT_OFFSET = UBOCameraEnum.VIEW_PORT_OFFSET; + public static readonly COUNT = UBOCameraEnum.COUNT; + public static readonly SIZE = UBOCameraEnum.SIZE; public static readonly NAME = 'CCCamera'; public static readonly BINDING = PipelineGlobalBindings.UBO_CAMERA; @@ -264,23 +300,39 @@ export class UBOCamera { globalDescriptorSetLayout.layouts[UBOCamera.NAME] = UBOCamera.LAYOUT; globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR; +export enum UBOShadowEnum { + MAT_LIGHT_VIEW_OFFSET = 0, + MAT_LIGHT_VIEW_PROJ_OFFSET = MAT_LIGHT_VIEW_OFFSET + 16, + SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = MAT_LIGHT_VIEW_PROJ_OFFSET + 16, + SHADOW_PROJ_DEPTH_INFO_OFFSET = SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4, + SHADOW_PROJ_INFO_OFFSET = SHADOW_PROJ_DEPTH_INFO_OFFSET + 4, + SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = SHADOW_PROJ_INFO_OFFSET + 4, + SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 4, + SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4, + SHADOW_COLOR_OFFSET = SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4, + PLANAR_NORMAL_DISTANCE_INFO_OFFSET = SHADOW_COLOR_OFFSET + 4, + COUNT = PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4, + SIZE = COUNT * 4, +} + /** * @en The uniform buffer object for 'cast shadow(fixed || csm)' && 'dir fixed area shadow' && 'spot shadow' && 'sphere shadow' && 'planar shadow' * @zh 这个 UBO 仅仅只给 'cast shadow(fixed || csm)' && 'dir fixed area shadow' && 'spot shadow' && 'sphere shadow' && 'planar shadow' 使用 */ export class UBOShadow { - public static readonly MAT_LIGHT_VIEW_OFFSET = 0; - public static readonly MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow.MAT_LIGHT_VIEW_OFFSET + 16; - public static readonly SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET + 16; - public static readonly SHADOW_PROJ_DEPTH_INFO_OFFSET = UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4; - public static readonly SHADOW_PROJ_INFO_OFFSET = UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 4; - public static readonly SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = UBOShadow.SHADOW_PROJ_INFO_OFFSET + 4; - public static readonly SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 4; - public static readonly SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4; - public static readonly SHADOW_COLOR_OFFSET = UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4; - public static readonly PLANAR_NORMAL_DISTANCE_INFO_OFFSET = UBOShadow.SHADOW_COLOR_OFFSET + 4; - public static readonly COUNT: number = UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; - public static readonly SIZE = UBOShadow.COUNT * 4; + public static readonly MAT_LIGHT_VIEW_OFFSET = UBOShadowEnum.MAT_LIGHT_VIEW_OFFSET; + public static readonly MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadowEnum.MAT_LIGHT_VIEW_PROJ_OFFSET; + public static readonly SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = UBOShadowEnum.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET; + public static readonly SHADOW_PROJ_DEPTH_INFO_OFFSET = UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET; + public static readonly SHADOW_PROJ_INFO_OFFSET = UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET; + public static readonly SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET; + public static readonly SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET; + public static readonly SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET; + public static readonly SHADOW_COLOR_OFFSET = UBOShadowEnum.SHADOW_COLOR_OFFSET; + public static readonly PLANAR_NORMAL_DISTANCE_INFO_OFFSET = UBOShadowEnum.PLANAR_NORMAL_DISTANCE_INFO_OFFSET; + public static readonly COUNT = UBOShadowEnum.COUNT; + public static readonly SIZE = UBOShadowEnum.SIZE; + public static readonly NAME = 'CCShadow'; public static readonly BINDING = PipelineGlobalBindings.UBO_SHADOW; public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOShadow.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL); @@ -300,22 +352,36 @@ export class UBOShadow { globalDescriptorSetLayout.layouts[UBOShadow.NAME] = UBOShadow.LAYOUT; globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR; +export enum UBOCSMEnum { + CSM_LEVEL_COUNT = 4, + CSM_VIEW_DIR_0_OFFSET = 0, + CSM_VIEW_DIR_1_OFFSET = CSM_VIEW_DIR_0_OFFSET + 4 * CSM_LEVEL_COUNT, + CSM_VIEW_DIR_2_OFFSET = CSM_VIEW_DIR_1_OFFSET + 4 * CSM_LEVEL_COUNT, + CSM_ATLAS_OFFSET = CSM_VIEW_DIR_2_OFFSET + 4 * CSM_LEVEL_COUNT, + MAT_CSM_VIEW_PROJ_OFFSET = CSM_ATLAS_OFFSET + 4 * CSM_LEVEL_COUNT, + CSM_PROJ_DEPTH_INFO_OFFSET = MAT_CSM_VIEW_PROJ_OFFSET + 16 * CSM_LEVEL_COUNT, + CSM_PROJ_INFO_OFFSET = CSM_PROJ_DEPTH_INFO_OFFSET + 4 * CSM_LEVEL_COUNT, + CSM_SPLITS_INFO_OFFSET = CSM_PROJ_INFO_OFFSET + 4 * CSM_LEVEL_COUNT, + COUNT = CSM_SPLITS_INFO_OFFSET + 4, + SIZE = COUNT * 4, +} + /** * @en The uniform buffer object only for dir csm shadow(level: 1 ~ 4) * @zh 级联阴影使用的UBO */ export class UBOCSM { - public static readonly CSM_LEVEL_COUNT = 4; - public static readonly CSM_VIEW_DIR_0_OFFSET = 0; - public static readonly CSM_VIEW_DIR_1_OFFSET = UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly CSM_VIEW_DIR_2_OFFSET = UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly CSM_ATLAS_OFFSET = UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOCSM.CSM_ATLAS_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly CSM_PROJ_INFO_OFFSET = UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly CSM_SPLITS_INFO_OFFSET = UBOCSM.CSM_PROJ_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; - public static readonly COUNT: number = UBOCSM.CSM_SPLITS_INFO_OFFSET + 4; - public static readonly SIZE = UBOCSM.COUNT * 4; + public static readonly CSM_LEVEL_COUNT = UBOCSMEnum.CSM_LEVEL_COUNT; + public static readonly CSM_VIEW_DIR_0_OFFSET = UBOCSMEnum.CSM_VIEW_DIR_0_OFFSET; + public static readonly CSM_VIEW_DIR_1_OFFSET = UBOCSMEnum.CSM_VIEW_DIR_1_OFFSET; + public static readonly CSM_VIEW_DIR_2_OFFSET = UBOCSMEnum.CSM_VIEW_DIR_2_OFFSET; + public static readonly CSM_ATLAS_OFFSET = UBOCSMEnum.CSM_ATLAS_OFFSET; + public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOCSMEnum.MAT_CSM_VIEW_PROJ_OFFSET; + public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOCSMEnum.CSM_PROJ_DEPTH_INFO_OFFSET; + public static readonly CSM_PROJ_INFO_OFFSET = UBOCSMEnum.CSM_PROJ_INFO_OFFSET; + public static readonly CSM_SPLITS_INFO_OFFSET = UBOCSMEnum.CSM_SPLITS_INFO_OFFSET; + public static readonly COUNT: number = UBOCSMEnum.COUNT; + public static readonly SIZE = UBOCSMEnum.SIZE; public static readonly NAME = 'CCCSM'; public static readonly BINDING = PipelineGlobalBindings.UBO_CSM; @@ -372,21 +438,34 @@ const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetInde globalDescriptorSetLayout.layouts[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT; globalDescriptorSetLayout.bindings[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR; +export enum UBOLocalEnum { + MAT_WORLD_OFFSET = 0, + MAT_WORLD_IT_OFFSET = MAT_WORLD_OFFSET + 16, + LIGHTINGMAP_UVPARAM = MAT_WORLD_IT_OFFSET + 16, + LOCAL_SHADOW_BIAS = LIGHTINGMAP_UVPARAM + 4, + REFLECTION_PROBE_DATA1 = LOCAL_SHADOW_BIAS + 4, + REFLECTION_PROBE_DATA2 = REFLECTION_PROBE_DATA1 + 4, + REFLECTION_PROBE_BLEND_DATA1 = REFLECTION_PROBE_DATA2 + 4, + REFLECTION_PROBE_BLEND_DATA2 = REFLECTION_PROBE_BLEND_DATA1 + 4, + COUNT = REFLECTION_PROBE_BLEND_DATA2 + 4, + SIZE = COUNT * 4, +} + /** * @en The local uniform buffer object * @zh 本地 UBO。 */ export class UBOLocal { - public static readonly MAT_WORLD_OFFSET = 0; - public static readonly MAT_WORLD_IT_OFFSET = UBOLocal.MAT_WORLD_OFFSET + 16; - public static readonly LIGHTINGMAP_UVPARAM = UBOLocal.MAT_WORLD_IT_OFFSET + 16; - public static readonly LOCAL_SHADOW_BIAS = UBOLocal.LIGHTINGMAP_UVPARAM + 4; - public static readonly REFLECTION_PROBE_DATA1 = UBOLocal.LOCAL_SHADOW_BIAS + 4; - public static readonly REFLECTION_PROBE_DATA2 = UBOLocal.REFLECTION_PROBE_DATA1 + 4; - public static readonly REFLECTION_PROBE_BLEND_DATA1 = UBOLocal.REFLECTION_PROBE_DATA2 + 4; - public static readonly REFLECTION_PROBE_BLEND_DATA2 = UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 4; - public static readonly COUNT = UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 4; - public static readonly SIZE = UBOLocal.COUNT * 4; + public static readonly MAT_WORLD_OFFSET = UBOLocalEnum.MAT_WORLD_OFFSET; + public static readonly MAT_WORLD_IT_OFFSET = UBOLocalEnum.MAT_WORLD_IT_OFFSET; + public static readonly LIGHTINGMAP_UVPARAM = UBOLocalEnum.LIGHTINGMAP_UVPARAM; + public static readonly LOCAL_SHADOW_BIAS = UBOLocalEnum.LOCAL_SHADOW_BIAS; + public static readonly REFLECTION_PROBE_DATA1 = UBOLocalEnum.REFLECTION_PROBE_DATA1; + public static readonly REFLECTION_PROBE_DATA2 = UBOLocalEnum.REFLECTION_PROBE_DATA2; + public static readonly REFLECTION_PROBE_BLEND_DATA1 = UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA1; + public static readonly REFLECTION_PROBE_BLEND_DATA2 = UBOLocalEnum.REFLECTION_PROBE_BLEND_DATA2; + public static readonly COUNT = UBOLocalEnum.COUNT; + public static readonly SIZE = UBOLocalEnum.SIZE; public static readonly NAME = 'CCLocal'; public static readonly BINDING = ModelLocalBindings.UBO_LOCAL; @@ -445,30 +524,41 @@ export class UBOLocalBatched { localDescriptorSetLayout.layouts[UBOLocalBatched.NAME] = UBOLocalBatched.LAYOUT; localDescriptorSetLayout.bindings[UBOLocalBatched.BINDING] = UBOLocalBatched.DESCRIPTOR; +export enum UBOForwardLightEnum { + LIGHTS_PER_PASS = 1, + LIGHT_POS_OFFSET = 0, + LIGHT_COLOR_OFFSET = LIGHT_POS_OFFSET + LIGHTS_PER_PASS * 4, + LIGHT_SIZE_RANGE_ANGLE_OFFSET = LIGHT_COLOR_OFFSET + LIGHTS_PER_PASS * 4, + LIGHT_DIR_OFFSET = LIGHT_SIZE_RANGE_ANGLE_OFFSET + LIGHTS_PER_PASS * 4, + LIGHT_BOUNDING_SIZE_VS_OFFSET = LIGHT_DIR_OFFSET + LIGHTS_PER_PASS * 4, + COUNT = LIGHT_BOUNDING_SIZE_VS_OFFSET + LIGHTS_PER_PASS * 4, + SIZE = COUNT * 4, +} + /** * @en The uniform buffer object for forward lighting * @zh 前向灯光 UBO。 */ export class UBOForwardLight { - public static readonly LIGHTS_PER_PASS = 1; + public static readonly LIGHTS_PER_PASS = UBOForwardLightEnum.LIGHTS_PER_PASS; - public static readonly LIGHT_POS_OFFSET = 0; - public static readonly LIGHT_COLOR_OFFSET = UBOForwardLight.LIGHT_POS_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4; - public static readonly LIGHT_SIZE_RANGE_ANGLE_OFFSET = UBOForwardLight.LIGHT_COLOR_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4; - public static readonly LIGHT_DIR_OFFSET = UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4; - public static readonly LIGHT_BOUNDING_SIZE_VS_OFFSET = UBOForwardLight.LIGHT_DIR_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4; - public static readonly COUNT = UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET + UBOForwardLight.LIGHTS_PER_PASS * 4; - public static readonly SIZE = UBOForwardLight.COUNT * 4; + public static readonly LIGHT_POS_OFFSET = UBOForwardLightEnum.LIGHT_POS_OFFSET; + public static readonly LIGHT_COLOR_OFFSET = UBOForwardLightEnum.LIGHT_COLOR_OFFSET; + public static readonly LIGHT_SIZE_RANGE_ANGLE_OFFSET = UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET; + public static readonly LIGHT_DIR_OFFSET = UBOForwardLightEnum.LIGHT_DIR_OFFSET; + public static readonly LIGHT_BOUNDING_SIZE_VS_OFFSET = UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET; + public static readonly COUNT = UBOForwardLightEnum.COUNT; + public static readonly SIZE = UBOForwardLightEnum.SIZE; public static readonly NAME = 'CCForwardLight'; public static readonly BINDING = ModelLocalBindings.UBO_FORWARD_LIGHTS; public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOForwardLight.BINDING, DescriptorType.DYNAMIC_UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT); public static readonly LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOForwardLight.BINDING, UBOForwardLight.NAME, [ - new Uniform('cc_lightPos', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), - new Uniform('cc_lightColor', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), - new Uniform('cc_lightSizeRangeAngle', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), - new Uniform('cc_lightDir', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), - new Uniform('cc_lightBoundingSizeVS', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS), + new Uniform('cc_lightPos', Type.FLOAT4, UBOForwardLightEnum.LIGHTS_PER_PASS), + new Uniform('cc_lightColor', Type.FLOAT4, UBOForwardLightEnum.LIGHTS_PER_PASS), + new Uniform('cc_lightSizeRangeAngle', Type.FLOAT4, UBOForwardLightEnum.LIGHTS_PER_PASS), + new Uniform('cc_lightDir', Type.FLOAT4, UBOForwardLightEnum.LIGHTS_PER_PASS), + new Uniform('cc_lightBoundingSizeVS', Type.FLOAT4, UBOForwardLightEnum.LIGHTS_PER_PASS), ], 1); } localDescriptorSetLayout.layouts[UBOForwardLight.NAME] = UBOForwardLight.LAYOUT; @@ -550,24 +640,34 @@ export function localDescriptorSetLayout_ResizeMaxJoints (maxCount: number): voi localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR; } +export enum UBOMorphEnum { + MAX_MORPH_TARGET_COUNT = 60, + OFFSET_OF_WEIGHTS = 0, + OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 4 * MAX_MORPH_TARGET_COUNT, + OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH + 4, + OFFSET_OF_VERTICES_COUNT = OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT + 4, + COUNT_BASE_4_BYTES = 4 * (MAX_MORPH_TARGET_COUNT / 4) + 4, + SIZE = COUNT_BASE_4_BYTES * 4, +} + /** * @en The uniform buffer object for morph setting * @zh 形变配置的 UBO */ export class UBOMorph { - public static readonly MAX_MORPH_TARGET_COUNT = 60; - public static readonly OFFSET_OF_WEIGHTS = 0; - public static readonly OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 4 * UBOMorph.MAX_MORPH_TARGET_COUNT; - public static readonly OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH + 4; - public static readonly OFFSET_OF_VERTICES_COUNT = UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT + 4; - public static readonly COUNT_BASE_4_BYTES = 4 * Math.ceil(UBOMorph.MAX_MORPH_TARGET_COUNT / 4) + 4; - public static readonly SIZE = UBOMorph.COUNT_BASE_4_BYTES * 4; + public static readonly MAX_MORPH_TARGET_COUNT = UBOMorphEnum.MAX_MORPH_TARGET_COUNT; + public static readonly OFFSET_OF_WEIGHTS = UBOMorphEnum.OFFSET_OF_WEIGHTS; + public static readonly OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = UBOMorphEnum.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH; + public static readonly OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = UBOMorphEnum.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT; + public static readonly OFFSET_OF_VERTICES_COUNT = UBOMorphEnum.OFFSET_OF_VERTICES_COUNT; + public static readonly COUNT_BASE_4_BYTES = UBOMorphEnum.COUNT_BASE_4_BYTES; + public static readonly SIZE = UBOMorphEnum.SIZE; public static readonly NAME = 'CCMorph'; public static readonly BINDING = ModelLocalBindings.UBO_MORPH; public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOMorph.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX); public static readonly LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOMorph.BINDING, UBOMorph.NAME, [ - new Uniform('cc_displacementWeights', Type.FLOAT4, UBOMorph.MAX_MORPH_TARGET_COUNT / 4), + new Uniform('cc_displacementWeights', Type.FLOAT4, UBOMorphEnum.MAX_MORPH_TARGET_COUNT / 4), new Uniform('cc_displacementTextureInfo', Type.FLOAT4, 1), ], 1); } @@ -586,20 +686,32 @@ export class UBOUILocal { // pre one vec4 localDescriptorSetLayout.layouts[UBOUILocal.NAME] = UBOUILocal.LAYOUT; localDescriptorSetLayout.bindings[UBOUILocal.BINDING] = UBOUILocal.DESCRIPTOR; +export enum UBOSHEnum { + SH_LINEAR_CONST_R_OFFSET = 0, + SH_LINEAR_CONST_G_OFFSET = SH_LINEAR_CONST_R_OFFSET + 4, + SH_LINEAR_CONST_B_OFFSET = SH_LINEAR_CONST_G_OFFSET + 4, + SH_QUADRATIC_R_OFFSET = SH_LINEAR_CONST_B_OFFSET + 4, + SH_QUADRATIC_G_OFFSET = SH_QUADRATIC_R_OFFSET + 4, + SH_QUADRATIC_B_OFFSET = SH_QUADRATIC_G_OFFSET + 4, + SH_QUADRATIC_A_OFFSET = SH_QUADRATIC_B_OFFSET + 4, + COUNT = SH_QUADRATIC_A_OFFSET + 4, + SIZE = COUNT * 4, +} + /** * @en The SH uniform buffer object * @zh 球谐 UBO。 */ export class UBOSH { - public static readonly SH_LINEAR_CONST_R_OFFSET = 0; - public static readonly SH_LINEAR_CONST_G_OFFSET = UBOSH.SH_LINEAR_CONST_R_OFFSET + 4; - public static readonly SH_LINEAR_CONST_B_OFFSET = UBOSH.SH_LINEAR_CONST_G_OFFSET + 4; - public static readonly SH_QUADRATIC_R_OFFSET = UBOSH.SH_LINEAR_CONST_B_OFFSET + 4; - public static readonly SH_QUADRATIC_G_OFFSET = UBOSH.SH_QUADRATIC_R_OFFSET + 4; - public static readonly SH_QUADRATIC_B_OFFSET = UBOSH.SH_QUADRATIC_G_OFFSET + 4; - public static readonly SH_QUADRATIC_A_OFFSET = UBOSH.SH_QUADRATIC_B_OFFSET + 4; - public static readonly COUNT = UBOSH.SH_QUADRATIC_A_OFFSET + 4; - public static readonly SIZE = UBOSH.COUNT * 4; + public static readonly SH_LINEAR_CONST_R_OFFSET = UBOSHEnum.SH_LINEAR_CONST_R_OFFSET; + public static readonly SH_LINEAR_CONST_G_OFFSET = UBOSHEnum.SH_LINEAR_CONST_G_OFFSET; + public static readonly SH_LINEAR_CONST_B_OFFSET = UBOSHEnum.SH_LINEAR_CONST_B_OFFSET; + public static readonly SH_QUADRATIC_R_OFFSET = UBOSHEnum.SH_QUADRATIC_R_OFFSET; + public static readonly SH_QUADRATIC_G_OFFSET = UBOSHEnum.SH_QUADRATIC_G_OFFSET; + public static readonly SH_QUADRATIC_B_OFFSET = UBOSHEnum.SH_QUADRATIC_B_OFFSET; + public static readonly SH_QUADRATIC_A_OFFSET = UBOSHEnum.SH_QUADRATIC_A_OFFSET; + public static readonly COUNT = UBOSHEnum.COUNT; + public static readonly SIZE = UBOSHEnum.SIZE; public static readonly NAME = 'CCSH'; public static readonly BINDING = ModelLocalBindings.UBO_SH; diff --git a/cocos/rendering/global-descriptor-set-manager.ts b/cocos/rendering/global-descriptor-set-manager.ts index 77ab167c7cd..11de559ea79 100644 --- a/cocos/rendering/global-descriptor-set-manager.ts +++ b/cocos/rendering/global-descriptor-set-manager.ts @@ -25,7 +25,7 @@ import { Device, BufferUsageBit, MemoryUsageBit, BufferInfo, Filter, Address, Sampler, DescriptorSet, DescriptorSetInfo, Buffer, Texture, DescriptorSetLayoutInfo, DescriptorSetLayout, SamplerInfo } from '../gfx'; import { Light } from '../render-scene/scene/light'; -import { UBOShadow, globalDescriptorSetLayout, PipelineGlobalBindings } from './define'; +import { UBOShadow, globalDescriptorSetLayout, PipelineGlobalBindings, UBOShadowEnum } from './define'; const _samplerLinearInfo = new SamplerInfo( Filter.LINEAR, @@ -190,8 +190,8 @@ export class GlobalDSManager { const shadowUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOShadow.SIZE, - UBOShadow.SIZE, + UBOShadowEnum.SIZE, + UBOShadowEnum.SIZE, )); descriptorSet.bindBuffer(UBOShadow.BINDING, shadowUBO); diff --git a/cocos/rendering/pipeline-ubo.ts b/cocos/rendering/pipeline-ubo.ts index 6d4a198fa6c..85123ff68e1 100644 --- a/cocos/rendering/pipeline-ubo.ts +++ b/cocos/rendering/pipeline-ubo.ts @@ -22,9 +22,12 @@ THE SOFTWARE. */ -import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, +import { UBOGlobal, UBOShadow, UBOCamera, UBOCameraEnum, UNIFORM_SHADOWMAP_BINDING, supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM, isEnableEffect, - getDefaultShadowTexture } from './define'; + getDefaultShadowTexture, + UBOShadowEnum, + UBOGlobalEnum, + UBOCSMEnum } from './define'; import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../gfx'; import { Camera } from '../render-scene/scene/camera'; import { Mat4, Vec3, Vec4, Color, toRadian, cclegacy } from '../core'; @@ -53,41 +56,41 @@ export class PipelineUBO { const shadingHeight = Math.floor(window.height); // update UBOGlobal - fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime; - fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime; - fv[UBOGlobal.TIME_OFFSET + 2] = director.getTotalFrames(); - fv[UBOGlobal.TIME_OFFSET + 3] = root.cumulativeTime - Math.floor(root.frameTime); + fv[UBOGlobalEnum.TIME_OFFSET] = root.cumulativeTime; + fv[UBOGlobalEnum.TIME_OFFSET + 1] = root.frameTime; + fv[UBOGlobalEnum.TIME_OFFSET + 2] = director.getTotalFrames(); + fv[UBOGlobalEnum.TIME_OFFSET + 3] = root.cumulativeTime - Math.floor(root.frameTime); - fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 2] = 1.0 / shadingWidth; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 3] = 1.0 / shadingHeight; + fv[UBOGlobalEnum.SCREEN_SIZE_OFFSET] = shadingWidth; + fv[UBOGlobalEnum.SCREEN_SIZE_OFFSET + 1] = shadingHeight; + fv[UBOGlobalEnum.SCREEN_SIZE_OFFSET + 2] = 1.0 / shadingWidth; + fv[UBOGlobalEnum.SCREEN_SIZE_OFFSET + 3] = 1.0 / shadingHeight; - fv[UBOGlobal.NATIVE_SIZE_OFFSET] = shadingWidth; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1] = shadingHeight; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET]; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1]; + fv[UBOGlobalEnum.NATIVE_SIZE_OFFSET] = shadingWidth; + fv[UBOGlobalEnum.NATIVE_SIZE_OFFSET + 1] = shadingHeight; + fv[UBOGlobalEnum.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobalEnum.NATIVE_SIZE_OFFSET]; + fv[UBOGlobalEnum.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobalEnum.NATIVE_SIZE_OFFSET + 1]; if (cclegacy.internal.reflectionProbeManager) { // eslint-disable-next-line @typescript-eslint/restrict-plus-operands - fv[UBOGlobal.PROBE_INFO_OFFSET] = cclegacy.internal.reflectionProbeManager.getMaxProbeId() + 1; + fv[UBOGlobalEnum.PROBE_INFO_OFFSET] = cclegacy.internal.reflectionProbeManager.getMaxProbeId() + 1; } const debugView = root.debugView; for (let i = 0; i <= 3; i++) { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + i] = 0.0; + fv[UBOGlobalEnum.DEBUG_VIEW_MODE_OFFSET + i] = 0.0; } if (debugView.isEnabled()) { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode as number; + fv[UBOGlobalEnum.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode as number; for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < (DebugViewCompositeType.MAX_BIT_COUNT as unknown as number); i++) { const offset = i >> 3; const bit = i % 8; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1 + offset] += (debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0) * (10.0 ** bit); + fv[UBOGlobalEnum.DEBUG_VIEW_MODE_OFFSET + 1 + offset] += (debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0) * (10.0 ** bit); } - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.lightingWithAlbedo ? 1.0 : 0.0) * (10.0 ** 6.0); - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.csmLayerColoration ? 1.0 : 0.0) * (10.0 ** 7.0); + fv[UBOGlobalEnum.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.lightingWithAlbedo ? 1.0 : 0.0) * (10.0 ** 6.0); + fv[UBOGlobalEnum.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.csmLayerColoration ? 1.0 : 0.0) * (10.0 ** 7.0); } } @@ -108,38 +111,38 @@ export class PipelineUBO { const isHDR = sceneData.isHDR; // update camera ubo - cv[UBOCamera.SCREEN_SCALE_OFFSET] = sceneData.shadingScale; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 1] = sceneData.shadingScale; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET]; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET + 1]; + cv[UBOCameraEnum.SCREEN_SCALE_OFFSET] = sceneData.shadingScale; + cv[UBOCameraEnum.SCREEN_SCALE_OFFSET + 1] = sceneData.shadingScale; + cv[UBOCameraEnum.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCameraEnum.SCREEN_SCALE_OFFSET]; + cv[UBOCameraEnum.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCameraEnum.SCREEN_SCALE_OFFSET + 1]; - cv[UBOCamera.EXPOSURE_OFFSET] = exposure; - cv[UBOCamera.EXPOSURE_OFFSET + 1] = 1.0 / exposure; - cv[UBOCamera.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0; - cv[UBOCamera.EXPOSURE_OFFSET + 3] = 1.0 / Camera.standardExposureValue; + cv[UBOCameraEnum.EXPOSURE_OFFSET] = exposure; + cv[UBOCameraEnum.EXPOSURE_OFFSET + 1] = 1.0 / exposure; + cv[UBOCameraEnum.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0; + cv[UBOCameraEnum.EXPOSURE_OFFSET + 3] = 1.0 / Camera.standardExposureValue; if (mainLight) { const shadowEnable = (mainLight.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap) ? 1.0 : 0.0; const mainLightDir = mainLight.direction; _lightDir.set(mainLightDir.x, mainLightDir.y, mainLightDir.z, shadowEnable); - Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET); - Vec3.toArray(cv, mainLight.color, UBOCamera.MAIN_LIT_COLOR_OFFSET); + Vec4.toArray(cv, _lightDir, UBOCameraEnum.MAIN_LIT_DIR_OFFSET); + Vec3.toArray(cv, mainLight.color, UBOCameraEnum.MAIN_LIT_COLOR_OFFSET); if (mainLight.useColorTemperature) { const colorTempRGB = mainLight.colorTemperatureRGB; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET] *= colorTempRGB.x; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 1] *= colorTempRGB.y; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 2] *= colorTempRGB.z; + cv[UBOCameraEnum.MAIN_LIT_COLOR_OFFSET] *= colorTempRGB.x; + cv[UBOCameraEnum.MAIN_LIT_COLOR_OFFSET + 1] *= colorTempRGB.y; + cv[UBOCameraEnum.MAIN_LIT_COLOR_OFFSET + 2] *= colorTempRGB.z; } if (isHDR) { - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure; + cv[UBOCameraEnum.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure; } else { - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance; + cv[UBOCameraEnum.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance; } } else { _lightDir.set(0, 0, 1, 0); - Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET); - Vec4.toArray(cv, Vec4.ZERO, UBOCamera.MAIN_LIT_COLOR_OFFSET); + Vec4.toArray(cv, _lightDir, UBOCameraEnum.MAIN_LIT_DIR_OFFSET); + Vec4.toArray(cv, Vec4.ZERO, UBOCameraEnum.MAIN_LIT_COLOR_OFFSET); } const skyColor = ambient.skyColor; @@ -148,52 +151,52 @@ export class PipelineUBO { } else { skyColor.w = ambient.skyIllum; } - cv[UBOCamera.AMBIENT_SKY_OFFSET + 0] = skyColor.x; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 1] = skyColor.y; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 2] = skyColor.z; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 3] = skyColor.w; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 0] = ambient.groundAlbedo.x; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 1] = ambient.groundAlbedo.y; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 2] = ambient.groundAlbedo.z; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = skybox.envmap ? skybox.envmap?.mipmapLevel : 1.0; - - Mat4.toArray(cv, camera.matView, UBOCamera.MAT_VIEW_OFFSET); - Mat4.toArray(cv, camera.node.worldMatrix, UBOCamera.MAT_VIEW_INV_OFFSET); - Vec3.toArray(cv, camera.position, UBOCamera.CAMERA_POS_OFFSET); - - Mat4.toArray(cv, camera.matProj, UBOCamera.MAT_PROJ_OFFSET); - Mat4.toArray(cv, camera.matProjInv, UBOCamera.MAT_PROJ_INV_OFFSET); - Mat4.toArray(cv, camera.matViewProj, UBOCamera.MAT_VIEW_PROJ_OFFSET); - Mat4.toArray(cv, camera.matViewProjInv, UBOCamera.MAT_VIEW_PROJ_INV_OFFSET); - cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY(); - - cv[UBOCamera.SURFACE_TRANSFORM_OFFSET] = camera.surfaceTransform; - cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 1] = camera.cameraUsage; - cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 2] = Math.cos(toRadian(sceneData.skybox.getRotationAngle())); - cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 3] = Math.sin(toRadian(sceneData.skybox.getRotationAngle())); + cv[UBOCameraEnum.AMBIENT_SKY_OFFSET + 0] = skyColor.x; + cv[UBOCameraEnum.AMBIENT_SKY_OFFSET + 1] = skyColor.y; + cv[UBOCameraEnum.AMBIENT_SKY_OFFSET + 2] = skyColor.z; + cv[UBOCameraEnum.AMBIENT_SKY_OFFSET + 3] = skyColor.w; + cv[UBOCameraEnum.AMBIENT_GROUND_OFFSET + 0] = ambient.groundAlbedo.x; + cv[UBOCameraEnum.AMBIENT_GROUND_OFFSET + 1] = ambient.groundAlbedo.y; + cv[UBOCameraEnum.AMBIENT_GROUND_OFFSET + 2] = ambient.groundAlbedo.z; + cv[UBOCameraEnum.AMBIENT_GROUND_OFFSET + 3] = skybox.envmap ? skybox.envmap?.mipmapLevel : 1.0; + + Mat4.toArray(cv, camera.matView, UBOCameraEnum.MAT_VIEW_OFFSET); + Mat4.toArray(cv, camera.node.worldMatrix, UBOCameraEnum.MAT_VIEW_INV_OFFSET); + Vec3.toArray(cv, camera.position, UBOCameraEnum.CAMERA_POS_OFFSET); + + Mat4.toArray(cv, camera.matProj, UBOCameraEnum.MAT_PROJ_OFFSET); + Mat4.toArray(cv, camera.matProjInv, UBOCameraEnum.MAT_PROJ_INV_OFFSET); + Mat4.toArray(cv, camera.matViewProj, UBOCameraEnum.MAT_VIEW_PROJ_OFFSET); + Mat4.toArray(cv, camera.matViewProjInv, UBOCameraEnum.MAT_VIEW_PROJ_INV_OFFSET); + cv[UBOCameraEnum.CAMERA_POS_OFFSET + 3] = this.getCombineSignY(); + + cv[UBOCameraEnum.SURFACE_TRANSFORM_OFFSET] = camera.surfaceTransform; + cv[UBOCameraEnum.SURFACE_TRANSFORM_OFFSET + 1] = camera.cameraUsage; + cv[UBOCameraEnum.SURFACE_TRANSFORM_OFFSET + 2] = Math.cos(toRadian(sceneData.skybox.getRotationAngle())); + cv[UBOCameraEnum.SURFACE_TRANSFORM_OFFSET + 3] = Math.sin(toRadian(sceneData.skybox.getRotationAngle())); const colorTempRGB = fog.colorArray; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 1] = colorTempRGB.y; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 2] = colorTempRGB.z; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 3] = colorTempRGB.z; - - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart; - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd; - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity; - - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop; - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange; - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten; - - cv[UBOCamera.NEAR_FAR_OFFSET] = camera.nearClip; - cv[UBOCamera.NEAR_FAR_OFFSET + 1] = camera.farClip; - cv[UBOCamera.NEAR_FAR_OFFSET + 2] = camera.getClipSpaceMinz(); - - cv[UBOCamera.VIEW_PORT_OFFSET] = sceneData.shadingScale * camera.window.width * camera.viewport.x; - cv[UBOCamera.VIEW_PORT_OFFSET + 1] = sceneData.shadingScale * camera.window.height * camera.viewport.y; - cv[UBOCamera.VIEW_PORT_OFFSET + 2] = sceneData.shadingScale * camera.window.width * camera.viewport.z; - cv[UBOCamera.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w; + cv[UBOCameraEnum.GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x; + cv[UBOCameraEnum.GLOBAL_FOG_COLOR_OFFSET + 1] = colorTempRGB.y; + cv[UBOCameraEnum.GLOBAL_FOG_COLOR_OFFSET + 2] = colorTempRGB.z; + cv[UBOCameraEnum.GLOBAL_FOG_COLOR_OFFSET + 3] = colorTempRGB.z; + + cv[UBOCameraEnum.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart; + cv[UBOCameraEnum.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd; + cv[UBOCameraEnum.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity; + + cv[UBOCameraEnum.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop; + cv[UBOCameraEnum.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange; + cv[UBOCameraEnum.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten; + + cv[UBOCameraEnum.NEAR_FAR_OFFSET] = camera.nearClip; + cv[UBOCameraEnum.NEAR_FAR_OFFSET + 1] = camera.farClip; + cv[UBOCameraEnum.NEAR_FAR_OFFSET + 2] = camera.getClipSpaceMinz(); + + cv[UBOCameraEnum.VIEW_PORT_OFFSET] = sceneData.shadingScale * camera.window.width * camera.viewport.x; + cv[UBOCameraEnum.VIEW_PORT_OFFSET + 1] = sceneData.shadingScale * camera.window.height * camera.viewport.y; + cv[UBOCameraEnum.VIEW_PORT_OFFSET + 2] = sceneData.shadingScale * camera.window.width * camera.viewport.z; + cv[UBOCameraEnum.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w; } public static getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number { @@ -214,10 +217,10 @@ export class PipelineUBO { public static updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: Float32Array): void { Vec3.normalize(_tempVec3, shadowInfo.normal); - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3.z; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance; + shadowUBO[UBOShadowEnum.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; + shadowUBO[UBOShadowEnum.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; + shadowUBO[UBOShadowEnum.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3.z; + shadowUBO[UBOShadowEnum.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance; } public static updateShadowUBOView ( @@ -255,73 +258,73 @@ export class PipelineUBO { levelCount = 1; } - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); + Mat4.toArray(sv, matShadowView, UBOShadowEnum.MAT_LIGHT_VIEW_OFFSET); - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); + Mat4.toArray(sv, matShadowViewProj, UBOShadowEnum.MAT_LIGHT_VIEW_PROJ_OFFSET); _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, levelCount); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } else { const layerThreshold = this.getPCFRadius(shadowInfo, mainLight); for (let i = 0; i < mainLight.csmLevel; i++) { const layer = csmLayers.layers[i]; const matShadowView = layer.matShadowView; _vec4ShadowInfo.set(matShadowView.m00, matShadowView.m04, matShadowView.m08, layerThreshold); - Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * i); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSMEnum.CSM_VIEW_DIR_0_OFFSET + 4 * i); _vec4ShadowInfo.set(matShadowView.m01, matShadowView.m05, matShadowView.m09, layer.splitCameraNear); - Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * i); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSMEnum.CSM_VIEW_DIR_1_OFFSET + 4 * i); _vec4ShadowInfo.set(matShadowView.m02, matShadowView.m06, matShadowView.m10, layer.splitCameraFar); - Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * i); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSMEnum.CSM_VIEW_DIR_2_OFFSET + 4 * i); const csmAtlas = layer.csmAtlas; - Vec4.toArray(cv, csmAtlas, UBOCSM.CSM_ATLAS_OFFSET + 4 * i); + Vec4.toArray(cv, csmAtlas, UBOCSMEnum.CSM_ATLAS_OFFSET + 4 * i); const matShadowViewProj = layer.matShadowViewProj; - Mat4.toArray(cv, matShadowViewProj, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowViewProj, UBOCSMEnum.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); const matShadowProj = layer.matShadowProj; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; - cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; - - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; - cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; + cv[UBOCSMEnum.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; + cv[UBOCSMEnum.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; + cv[UBOCSMEnum.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; + cv[UBOCSMEnum.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; + + cv[UBOCSMEnum.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; + cv[UBOCSMEnum.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; + cv[UBOCSMEnum.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; + cv[UBOCSMEnum.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; } _vec4ShadowInfo.set(mainLight.csmTransitionRange, 0, 0, 0); - Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_SPLITS_INFO_OFFSET); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSMEnum.CSM_SPLITS_INFO_OFFSET); _vec4ShadowInfo.set(0.1, mainLight.shadowDistance, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, mainLight.csmLevel); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); } } else { PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, sv); _vec4ShadowInfo.set(0, 0, 0, shadowInfo.planeBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); } - Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); + Color.toArray(sv, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET); } } @@ -360,7 +363,7 @@ export class PipelineUBO { levelCount = 1; } _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, 0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } else { const layer = csmLayers.layers[level]; matShadowView = layer.matShadowView; @@ -372,28 +375,28 @@ export class PipelineUBO { levelCount = mainLight.csmLevel; } - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); + Mat4.toArray(sv, matShadowView, UBOShadowEnum.MAT_LIGHT_VIEW_OFFSET); - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; + sv[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; + sv[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); + Mat4.toArray(sv, matShadowViewProj, UBOShadowEnum.MAT_LIGHT_VIEW_PROJ_OFFSET); _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, levelCount); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); } } break; @@ -402,7 +405,7 @@ export class PipelineUBO { const spotLight = light as SpotLight; if (shadowInfo.enabled && spotLight && spotLight.shadowEnabled) { Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); - Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); + Mat4.toArray(sv, _matShadowView, UBOShadowEnum.MAT_LIGHT_VIEW_OFFSET); Mat4.perspective( _matShadowProj, @@ -417,29 +420,29 @@ export class PipelineUBO { ); Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); + Mat4.toArray(sv, _matShadowViewProj, UBOShadowEnum.MAT_LIGHT_VIEW_PROJ_OFFSET); _vec4ShadowInfo.set(0.01, (light as SpotLight).range, 0.0, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, spotLight.shadowPcf, spotLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); _vec4ShadowInfo.set(LightType.SPOT, packing, spotLight.shadowNormalBias, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); + Vec4.toArray(sv, _vec4ShadowInfo, UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } break; } default: } - Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); + Color.toArray(sv, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET); } - protected _globalUBO = new Float32Array(UBOGlobal.COUNT); - protected _cameraUBO = new Float32Array(UBOCamera.COUNT); - protected _shadowUBO = new Float32Array(UBOShadow.COUNT); - protected _csmUBO = new Float32Array(UBOCSM.COUNT); + protected _globalUBO = new Float32Array(UBOGlobalEnum.COUNT); + protected _cameraUBO = new Float32Array(UBOCameraEnum.COUNT); + protected _shadowUBO = new Float32Array(UBOShadowEnum.COUNT); + protected _csmUBO = new Float32Array(UBOCSMEnum.COUNT); static _combineSignY = 0; protected declare _device: Device; protected declare _pipeline: PipelineRuntime; @@ -473,30 +476,30 @@ export class PipelineUBO { const globalUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOGlobal.SIZE, - UBOGlobal.SIZE, + UBOGlobalEnum.SIZE, + UBOGlobalEnum.SIZE, )); ds.bindBuffer(UBOGlobal.BINDING, globalUBO); const cameraUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOCamera.SIZE, - UBOCamera.SIZE, + UBOCameraEnum.SIZE, + UBOCameraEnum.SIZE, )); ds.bindBuffer(UBOCamera.BINDING, cameraUBO); const shadowUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOShadow.SIZE, - UBOShadow.SIZE, + UBOShadowEnum.SIZE, + UBOShadowEnum.SIZE, )); ds.bindBuffer(UBOShadow.BINDING, shadowUBO); const csmUBO = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOCSM.SIZE, - UBOCSM.SIZE, + UBOCSMEnum.SIZE, + UBOCSMEnum.SIZE, )); ds.bindBuffer(UBOCSM.BINDING, csmUBO); } diff --git a/cocos/rendering/post-process/passes/forward-final-pass.ts b/cocos/rendering/post-process/passes/forward-final-pass.ts index 8452c212963..91f3839e480 100644 --- a/cocos/rendering/post-process/passes/forward-final-pass.ts +++ b/cocos/rendering/post-process/passes/forward-final-pass.ts @@ -1,6 +1,6 @@ import { Vec4 } from '../../../core'; import { ClearFlagBit, Format } from '../../../gfx'; -import { Camera, SKYBOX_FLAG } from '../../../render-scene/scene'; +import { Camera, SkyBoxFlagValue } from '../../../render-scene/scene'; import { getCameraUniqueID } from '../../custom/define'; import { Pipeline } from '../../custom/pipeline'; import { passContext } from '../utils/pass-context'; @@ -17,7 +17,7 @@ export class ForwardFinalPass extends BasePass { return; } - passContext.clearFlag = camera.clearFlag & ClearFlagBit.COLOR | (camera.clearFlag & SKYBOX_FLAG); + passContext.clearFlag = camera.clearFlag & ClearFlagBit.COLOR | (camera.clearFlag & SkyBoxFlagValue.VALUE); Vec4.set(passContext.clearColor, camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w); passContext.material = this.material; diff --git a/cocos/rendering/post-process/passes/forward-pass.ts b/cocos/rendering/post-process/passes/forward-pass.ts index c16d0b493c7..d3beae759a8 100644 --- a/cocos/rendering/post-process/passes/forward-pass.ts +++ b/cocos/rendering/post-process/passes/forward-pass.ts @@ -1,7 +1,7 @@ import { Vec4 } from '../../../core'; import { ClearFlagBit, Format } from '../../../gfx'; -import { Camera, ShadowType, SKYBOX_FLAG } from '../../../render-scene/scene'; +import { Camera, ShadowType, SkyBoxFlagValue } from '../../../render-scene/scene'; import { LightInfo, QueueHint, SceneFlags } from '../../custom/types'; import { getCameraUniqueID } from '../../custom/define'; import { Pipeline } from '../../custom/pipeline'; @@ -38,7 +38,7 @@ export class ForwardPass extends BasePass { } public render (camera: Camera, ppl: Pipeline): void { - passContext.clearFlag = ClearFlagBit.COLOR | (camera.clearFlag & ClearFlagBit.DEPTH_STENCIL) | (camera.clearFlag & SKYBOX_FLAG); + passContext.clearFlag = ClearFlagBit.COLOR | (camera.clearFlag & ClearFlagBit.DEPTH_STENCIL) | (camera.clearFlag & SkyBoxFlagValue.VALUE); Vec4.set(passContext.clearColor, 0, 0, 0, 0); Vec4.set(passContext.clearDepthColor, camera.clearDepth, camera.clearStencil, 0, 0); diff --git a/cocos/rendering/post-process/passes/hbao-pass.ts b/cocos/rendering/post-process/passes/hbao-pass.ts index f6f0e8a5893..b6daf002050 100644 --- a/cocos/rendering/post-process/passes/hbao-pass.ts +++ b/cocos/rendering/post-process/passes/hbao-pass.ts @@ -36,6 +36,7 @@ import { ImageAsset } from '../../../asset/assets/image-asset'; import { DebugViewCompositeType, DebugViewSingleType } from '../../debug-view'; import { ClearFlagBit, Format } from '../../../gfx'; import { Scene } from '../../../scene-graph/scene'; +import { Filter, PixelFormat, WrapMode } from '../../../asset/assets/asset-enum'; const vec2 = new Vec2(); @@ -118,7 +119,7 @@ class HBAOParams { private _init (): void { const width = 4; const height = 4; - const pixelFormat = Texture2D.PixelFormat.RGBA8888; + const pixelFormat = PixelFormat.RGBA8888; const arrayBuffer = new Uint8Array(width * height * 4); for (let i = 0; i < this._randomDirAndJitter.length; i++) { arrayBuffer[i] = this._randomDirAndJitter[i]; @@ -131,9 +132,9 @@ class HBAOParams { format: pixelFormat, }); this.randomTexture = new Texture2D(); - this.randomTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - this.randomTexture.setMipFilter(Texture2D.Filter.NONE); - this.randomTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + this.randomTexture.setFilters(Filter.NEAREST, Filter.NEAREST); + this.randomTexture.setMipFilter(Filter.NONE); + this.randomTexture.setWrapMode(WrapMode.REPEAT, WrapMode.REPEAT, WrapMode.REPEAT); this.randomTexture.image = image; } diff --git a/cocos/rendering/post-process/utils/pass-context.ts b/cocos/rendering/post-process/utils/pass-context.ts index 10df668fe5d..9c079430ffe 100644 --- a/cocos/rendering/post-process/utils/pass-context.ts +++ b/cocos/rendering/post-process/utils/pass-context.ts @@ -3,7 +3,7 @@ import { EDITOR } from 'internal:constants'; import { LightInfo, QueueHint, ResourceResidency, SceneFlags } from '../../custom/types'; import { ClearFlagBit, Color, Format, LoadOp, Rect, StoreOp, Viewport } from '../../../gfx'; import { Pipeline, RenderPassBuilder, RenderQueueBuilder } from '../../custom/pipeline'; -import { Camera, SKYBOX_FLAG } from '../../../render-scene/scene'; +import { Camera, SkyBoxFlagValue } from '../../../render-scene/scene'; import { Material } from '../../../asset/assets'; import { PostProcess } from '../components'; import { getRenderArea } from '../../custom/define'; @@ -222,9 +222,9 @@ export class PassContext { const clearFlag = this.clearFlag & ClearFlagBit.COLOR; let loadOp = LoadOp.CLEAR; - if (clearFlag === ClearFlagBit.NONE && !(this.clearFlag & SKYBOX_FLAG)) { + if (clearFlag === ClearFlagBit.NONE && !(this.clearFlag & SkyBoxFlagValue.VALUE)) { loadOp = LoadOp.LOAD; - } else if (this.clearFlag & SKYBOX_FLAG) { + } else if (this.clearFlag & SkyBoxFlagValue.VALUE) { clearColor.set(0, 0, 0, 1); } pass.addRenderTarget(name, loadOp, StoreOp.STORE, clearColor); diff --git a/cocos/rendering/render-additive-light-queue.ts b/cocos/rendering/render-additive-light-queue.ts index c191fa6b54e..708c1cccc52 100644 --- a/cocos/rendering/render-additive-light-queue.ts +++ b/cocos/rendering/render-additive-light-queue.ts @@ -36,8 +36,11 @@ import { RangedDirectionalLight } from '../render-scene/scene/ranged-directional import { SubModel } from '../render-scene/scene/submodel'; import { getPhaseID } from './pass-phase'; import { Light, LightType } from '../render-scene/scene/light'; -import { SetIndex, UBOForwardLight, UBOShadow, UNIFORM_SHADOWMAP_BINDING, - UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, supportsR32FloatTexture, isEnableEffect } from './define'; +import { SetIndex, UBOShadow, UNIFORM_SHADOWMAP_BINDING, + UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, supportsR32FloatTexture, isEnableEffect, + UBOShadowEnum, + UBOForwardLightEnum, + UBOForwardLight } from './define'; import { Camera } from '../render-scene/scene/camera'; import { ShadowType } from '../render-scene/scene/shadows'; import { GlobalDSManager } from './global-descriptor-set-manager'; @@ -116,7 +119,7 @@ export class RenderAdditiveLightQueue { private declare _device: Device; private _lightPasses: IAdditiveLightPass[] = []; private _instancedLightPassPool = _lightPassPool.alloc(); - private _shadowUBO = new Float32Array(UBOShadow.COUNT); + private _shadowUBO = new Float32Array(UBOShadowEnum.COUNT); private _lightBufferCount = 16; private declare _lightBufferStride: number; private declare _lightBufferElementCount: number; @@ -131,7 +134,7 @@ export class RenderAdditiveLightQueue { this._device = pipeline.device; const alignment = this._device.capabilities.uboOffsetAlignment; - this._lightBufferStride = Math.ceil(UBOForwardLight.SIZE / alignment) * alignment; + this._lightBufferStride = Math.ceil(UBOForwardLightEnum.SIZE / alignment) * alignment; this._lightBufferElementCount = this._lightBufferStride / Float32Array.BYTES_PER_ELEMENT; this._lightBuffer = this._device.createBuffer(new BufferInfo( @@ -141,7 +144,7 @@ export class RenderAdditiveLightQueue { this._lightBufferStride, )); - this._firstLightBufferView = this._device.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE)); + this._firstLightBufferView = this._device.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLightEnum.SIZE)); this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount); } @@ -358,18 +361,18 @@ export class RenderAdditiveLightQueue { PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); } - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPHERE; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPHERE; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; // Reserve sphere light shadow interface - Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); + Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET); break; } case LightType.SPOT: { @@ -401,40 +404,40 @@ export class RenderAdditiveLightQueue { // light viewProj Mat4.multiply(_matShadowViewProj, _matShadowViewProj, _matShadowView); - Mat4.toArray(this._shadowUBO, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - Mat4.toArray(this._shadowUBO, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); + Mat4.toArray(this._shadowUBO, _matShadowView, UBOShadowEnum.MAT_LIGHT_VIEW_OFFSET); + Mat4.toArray(this._shadowUBO, _matShadowViewProj, UBOShadowEnum.MAT_LIGHT_VIEW_PROJ_OFFSET); - this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = 0.01; - this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = (light as SpotLight).range; - this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = 0.0; - this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = 0.01; + this._shadowUBO[UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = (light as SpotLight).range; + this._shadowUBO[UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 0.0; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = spotLight.shadowPcf; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = spotLight.shadowBias; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = spotLight.shadowPcf; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = spotLight.shadowBias; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPOT; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = spotLight.shadowNormalBias; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPOT; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = spotLight.shadowNormalBias; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; - this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; - this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; - this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; - this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; - this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowInvProj.m10; - this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowInvProj.m14; - this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowInvProj.m11; - this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowInvProj.m15; + this._shadowUBO[UBOShadowEnum.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowInvProj.m10; + this._shadowUBO[UBOShadowEnum.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowInvProj.m14; + this._shadowUBO[UBOShadowEnum.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowInvProj.m11; + this._shadowUBO[UBOShadowEnum.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowInvProj.m15; - this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; - this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; - this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; - this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; + this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; - Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); + Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET); // Spot light sampler binding if (shadowFrameBufferMap.has(light)) { @@ -451,18 +454,18 @@ export class RenderAdditiveLightQueue { PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); } - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0; - this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0; + this._shadowUBO[UBOShadowEnum.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.POINT; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0; - this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.POINT; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0; + this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; // Reserve point light shadow interface - Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); + Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET); break; } default: @@ -486,7 +489,7 @@ export class RenderAdditiveLightQueue { this._lightBuffer.resize(this._lightBufferStride * this._lightBufferCount); this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount); - this._firstLightBufferView = deviceManager.gfxDevice.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE)); + this._firstLightBufferView = deviceManager.gfxDevice.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLightEnum.SIZE)); } for (let l = 0, offset = 0; l < validPunctualLights.length; l++, offset += this._lightBufferElementCount) { @@ -497,13 +500,13 @@ export class RenderAdditiveLightQueue { // UBOForwardLight Vec3.toArray(_vec4Array, (light as SphereLight).position); _vec4Array[3] = LightType.SPHERE; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_POS_OFFSET); _vec4Array[0] = (light as SphereLight).size; _vec4Array[1] = (light as SphereLight).range; _vec4Array[2] = 0.0; _vec4Array[3] = 0.0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET); // cc_lightColor Vec3.toArray(_vec4Array, light.color); @@ -518,22 +521,22 @@ export class RenderAdditiveLightQueue { } else { _vec4Array[3] = (light as SphereLight).luminance; } - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_COLOR_OFFSET); break; case LightType.SPOT: // UBOForwardLight Vec3.toArray(_vec4Array, (light as SpotLight).position); _vec4Array[3] = LightType.SPOT; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_POS_OFFSET); _vec4Array[0] = (light as SpotLight).size; _vec4Array[1] = (light as SpotLight).range; _vec4Array[2] = (light as SpotLight).spotAngle; _vec4Array[3] = (shadowInfo.enabled && (light as SpotLight).shadowEnabled && shadowInfo.type === ShadowType.ShadowMap) ? 1 : 0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET); Vec3.toArray(_vec4Array, (light as SpotLight).direction); - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_DIR_OFFSET); // cc_lightColor Vec3.toArray(_vec4Array, light.color); @@ -548,26 +551,26 @@ export class RenderAdditiveLightQueue { } else { _vec4Array[3] = (light as SpotLight).luminance; } - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_COLOR_OFFSET); // cc_lightBoundingSizeVS, light angle attenuation strength _vec4Array[0] = 0; _vec4Array[1] = 0; _vec4Array[2] = 0; _vec4Array[3] = (light as SpotLight).angleAttenuationStrength; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET); break; case LightType.POINT: // UBOForwardLight Vec3.toArray(_vec4Array, (light as PointLight).position); _vec4Array[3] = LightType.POINT; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_POS_OFFSET); _vec4Array[0] = 0.0; _vec4Array[1] = (light as PointLight).range; _vec4Array[2] = 0.0; _vec4Array[3] = 0.0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET); // cc_lightColor Vec3.toArray(_vec4Array, light.color); @@ -582,28 +585,28 @@ export class RenderAdditiveLightQueue { } else { _vec4Array[3] = (light as PointLight).luminance; } - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_COLOR_OFFSET); break; case LightType.RANGED_DIRECTIONAL: // UBOForwardLight Vec3.toArray(_vec4Array, (light as RangedDirectionalLight).position); _vec4Array[3] = LightType.RANGED_DIRECTIONAL; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_POS_OFFSET); Vec3.toArray(_vec4Array, (light as RangedDirectionalLight).right); _vec4Array[3] = 0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_SIZE_RANGE_ANGLE_OFFSET); Vec3.toArray(_vec4Array, (light as RangedDirectionalLight).direction); _vec4Array[3] = 0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_DIR_OFFSET); // eslint-disable-next-line no-case-declarations const scale = (light as RangedDirectionalLight).scale; _v3.set(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5); Vec3.toArray(_vec4Array, _v3); _vec4Array[3] = 0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_BOUNDING_SIZE_VS_OFFSET); // cc_lightColor Vec3.toArray(_vec4Array, light.color); @@ -618,7 +621,7 @@ export class RenderAdditiveLightQueue { } else { _vec4Array[3] = (light as RangedDirectionalLight).illuminance; } - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLightEnum.LIGHT_COLOR_OFFSET); break; default: } diff --git a/cocos/rendering/render-pipeline.ts b/cocos/rendering/render-pipeline.ts index a1f035e7c33..46a720b246c 100644 --- a/cocos/rendering/render-pipeline.ts +++ b/cocos/rendering/render-pipeline.ts @@ -33,7 +33,7 @@ import { AccessFlagBit, Attribute, Buffer, BufferInfo, BufferUsageBit, ClearFlag } from '../gfx'; import { MacroRecord } from '../render-scene/core/pass-utils'; import { RenderWindow } from '../render-scene/core/render-window'; -import { Camera, SKYBOX_FLAG } from '../render-scene/scene/camera'; +import { Camera, SkyBoxFlagValue } from '../render-scene/scene/camera'; import { Model } from '../render-scene/scene/model'; import { GlobalDSManager } from './global-descriptor-set-manager'; import { GeometryRenderer } from './geometry-renderer'; @@ -300,7 +300,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi depthStencilAttachment.depthStoreOp = StoreOp.DISCARD; if (!(clearFlags & ClearFlagBit.COLOR)) { - if (clearFlags & SKYBOX_FLAG) { + if (clearFlags & SkyBoxFlagValue.VALUE) { colorAttachment.loadOp = LoadOp.CLEAR; } else { colorAttachment.loadOp = LoadOp.LOAD; diff --git a/cocos/rendering/render-reflection-probe-queue.ts b/cocos/rendering/render-reflection-probe-queue.ts index 5e19d942d71..77131fa1c39 100644 --- a/cocos/rendering/render-reflection-probe-queue.ts +++ b/cocos/rendering/render-reflection-probe-queue.ts @@ -30,7 +30,7 @@ import { PipelineStateManager } from './pipeline-state-manager'; import { Pass, BatchingSchemes, IMacroPatch } from '../render-scene/core/pass'; import { Model } from '../render-scene/scene/model'; import { ProbeType, ReflectionProbe } from '../render-scene/scene/reflection-probe'; -import { Camera, SKYBOX_FLAG } from '../render-scene/scene/camera'; +import { Camera, SkyBoxFlagValue } from '../render-scene/scene/camera'; import { PipelineRuntime } from './custom/pipeline'; import { RenderInstancedQueue } from './render-instanced-queue'; import { cclegacy, geometry } from '../core'; @@ -85,7 +85,7 @@ export class RenderReflectionProbeQueue { const sceneData = this._pipeline.pipelineSceneData; const skybox = sceneData.skybox; - if (skybox.enabled && skybox.model && (probe.camera.clearFlag & SKYBOX_FLAG)) { + if (skybox.enabled && skybox.model && (probe.camera.clearFlag & SkyBoxFlagValue.VALUE)) { this.add(skybox.model); } diff --git a/cocos/rendering/scene-culling.ts b/cocos/rendering/scene-culling.ts index 2e3f36c5e74..1cd156c2d2d 100644 --- a/cocos/rendering/scene-culling.ts +++ b/cocos/rendering/scene-culling.ts @@ -22,10 +22,10 @@ THE SOFTWARE. */ import { Model } from '../render-scene/scene/model'; -import { Camera, CameraUsage, SKYBOX_FLAG } from '../render-scene/scene/camera'; +import { Camera, CameraUsage, SkyBoxFlagValue } from '../render-scene/scene/camera'; import { Vec3, Pool, geometry, cclegacy } from '../core'; import { PipelineUBO } from './pipeline-ubo'; -import { IRenderObject, UBOShadow } from './define'; +import { IRenderObject, UBOShadowEnum } from './define'; import { ShadowType, CSMOptimizationMode } from '../render-scene/scene/shadows'; import { PipelineSceneData } from './pipeline-scene-data'; import { ShadowLayerVolume } from './shadow/csm-layers'; @@ -162,7 +162,7 @@ export function sceneCulling (sceneData: PipelineSceneData, pipelineUBO: Pipelin csmLayerObjects.clear(); if (shadows.enabled) { - pipelineUBO.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); + pipelineUBO.updateShadowUBORange(UBOShadowEnum.SHADOW_COLOR_OFFSET, shadows.shadowColor); if (shadows.type === ShadowType.ShadowMap) { // update CSM layers if (mainLight && mainLight.node) { @@ -171,7 +171,7 @@ export function sceneCulling (sceneData: PipelineSceneData, pipelineUBO: Pipelin } } - if ((camera.clearFlag & SKYBOX_FLAG)) { + if ((camera.clearFlag & SkyBoxFlagValue.VALUE)) { if (skybox.enabled && skybox.model) { renderObjects.push(getRenderObject(skybox.model, camera)); } else if (camera.cameraUsage !== CameraUsage.EDITOR && camera.cameraUsage !== CameraUsage.SCENE_VIEW) { diff --git a/cocos/rendering/shadow/shadow-flow.ts b/cocos/rendering/shadow/shadow-flow.ts index dddba6c9da9..c25199b0a37 100644 --- a/cocos/rendering/shadow/shadow-flow.ts +++ b/cocos/rendering/shadow/shadow-flow.ts @@ -23,7 +23,7 @@ */ import { ccclass } from 'cc.decorator'; -import { PIPELINE_FLOW_SHADOW, supportsR32FloatTexture, UBOCamera, UBOCSM, UBOGlobal, UBOShadow } from '../define'; +import { PIPELINE_FLOW_SHADOW, supportsR32FloatTexture, UBOCameraEnum, UBOCSMEnum, UBOGlobalEnum, UBOShadowEnum } from '../define'; import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { ForwardFlowPriority } from '../enum'; import { ShadowStage } from './shadow-stage'; @@ -88,7 +88,7 @@ export class ShadowFlow extends RenderFlow { // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. pipeline.pipelineSceneData.csmSupported = pipeline.device.capabilities.maxFragmentUniformVectors - >= (UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOCSM.COUNT) / 4; + >= (UBOGlobalEnum.COUNT + UBOCameraEnum.COUNT + UBOShadowEnum.COUNT + UBOCSMEnum.COUNT) / 4; pipeline.macros.CC_SUPPORT_CASCADED_SHADOW_MAP = pipeline.pipelineSceneData.csmSupported; // 0: CC_SHADOW_NONE, 1: CC_SHADOW_PLANAR, 2: CC_SHADOW_MAP diff --git a/cocos/root.ts b/cocos/root.ts index e7a417c228d..269249cb178 100644 --- a/cocos/root.ts +++ b/cocos/root.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import { Pool, cclegacy, warnID, settings, Settings, macro, log, errorID } from './core'; +import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory } from './core'; import { DebugView } from './rendering/debug-view'; import { Camera, CameraType, Light, Model, TrackingType } from './render-scene/scene'; import type { DataPoolManager } from './3d/skeletal-animation/data-pool-manager'; @@ -34,11 +34,11 @@ import { SpotLight } from './render-scene/scene/spot-light'; import { PointLight } from './render-scene/scene/point-light'; import { RangedDirectionalLight } from './render-scene/scene/ranged-directional-light'; import { RenderWindow, IRenderWindowInfo } from './render-scene/core/render-window'; -import { ColorAttachment, DepthStencilAttachment, RenderPassInfo, StoreOp, Device, Swapchain, Feature, deviceManager, LegacyRenderMode } from './gfx'; +import { ColorAttachment, DepthStencilAttachment, RenderPassInfo, StoreOp, Device, Swapchain, deviceManager, LegacyRenderMode } from './gfx'; import { BasicPipeline, PipelineRuntime } from './rendering/custom/pipeline'; import { Batcher2D } from './2d/renderer/batcher-2d'; import { IPipelineEvent, PipelineEventProcessor } from './rendering/pipeline-event'; -import { localDescriptorSetLayout_ResizeMaxJoints, UBOCamera, UBOGlobal, UBOLocal, UBOShadow, UBOWorldBound } from './rendering/define'; +import { localDescriptorSetLayout_ResizeMaxJoints, UBOCameraEnum, UBOGlobalEnum, UBOLocalEnum, UBOShadowEnum, UBOWorldBound } from './rendering/define'; import { XREye, XRPoseType } from './xr/xr-enums'; import { ICustomJointTextureLayout } from './3d/skeletal-animation/skeletal-animation-utils'; @@ -68,7 +68,7 @@ export class Root { * @zh GFX 设备 */ public get device (): Device { - return this._device; + return this._device$; } /** @@ -76,7 +76,7 @@ export class Root { * @zh 主窗口 */ public get mainWindow (): RenderWindow | null { - return this._mainWindow; + return this._mainWindow$; } /** @@ -84,11 +84,11 @@ export class Root { * @zh 当前激活的窗口 */ public set curWindow (window: RenderWindow | null) { - this._curWindow = window; + this._curWindow$ = window; } public get curWindow (): RenderWindow | null { - return this._curWindow; + return this._curWindow$; } /** @@ -97,11 +97,11 @@ export class Root { * @internal */ public set tempWindow (window: RenderWindow | null) { - this._tempWindow = window; + this._tempWindow$ = window; } public get tempWindow (): RenderWindow | null { - return this._tempWindow; + return this._tempWindow$; } /** @@ -109,7 +109,7 @@ export class Root { * @zh 窗口列表 */ public get windows (): RenderWindow[] { - return this._windows; + return this._windows$; } /** @@ -117,7 +117,7 @@ export class Root { * 启用自定义渲染管线 */ public get usesCustomPipeline (): boolean { - return this._usesCustomPipeline; + return this._usesCustomPipeline$; } /** @@ -125,7 +125,7 @@ export class Root { * @zh 渲染管线 */ public get pipeline (): PipelineRuntime { - return this._pipeline!; + return this._pipeline$!; } /** @@ -133,7 +133,7 @@ export class Root { * @zh 自定义渲染管线 */ public get customPipeline (): BasicPipeline { - return this._customPipeline!; + return this._customPipeline$!; } /** @@ -141,7 +141,7 @@ export class Root { * @zh 渲染管线事件 */ public get pipelineEvent (): IPipelineEvent { - return this._pipelineEvent!; + return this._pipelineEvent$!; } /** @@ -149,7 +149,7 @@ export class Root { * @zh 2D UI 渲染合批管理器,引擎内部使用,用户无需使用此接口 */ public get batcher2D (): Batcher2D { - return this._batcher as Batcher2D; + return this._batcher$ as Batcher2D; } /** @@ -157,7 +157,7 @@ export class Root { * @zh 渲染场景列表 */ public get scenes (): RenderScene[] { - return this._scenes; + return this._scenes$; } /** @@ -165,7 +165,7 @@ export class Root { * @zh 渲染调试管理器 */ public get debugView (): DebugView { - return this._debugView; + return this._debugView$; } /** @@ -173,7 +173,7 @@ export class Root { * @zh 累计时间(秒)。 */ public get cumulativeTime (): number { - return this._cumulativeTime; + return this._cumulativeTime$; } /** @@ -181,7 +181,7 @@ export class Root { * @zh 帧时间(秒)。 */ public get frameTime (): number { - return this._frameTime; + return this._frameTime$; } /** @@ -189,7 +189,7 @@ export class Root { * @zh 一秒内的累计帧数 */ public get frameCount (): number { - return this._frameCount; + return this._frameCount$; } /** @@ -197,7 +197,7 @@ export class Root { * @zh 当前每秒帧率 */ public get fps (): number { - return this._fps; + return this._fps$; } /** @@ -206,22 +206,19 @@ export class Root { */ public set fixedFPS (fps: number) { if (fps > 0) { - this._fixedFPS = fps; - this._fixedFPSFrameTime = 1000.0 / fps; - } else { - this._fixedFPSFrameTime = 0; + this._fixedFPS$ = fps; } } public get fixedFPS (): number { - return this._fixedFPS; + return this._fixedFPS$; } /** * @internal */ public get dataPoolManager (): DataPoolManager { - return this._dataPoolMgr; + return this._dataPoolMgr$; } /** @@ -229,11 +226,11 @@ export class Root { * @zh 是否启用内置延迟渲染管线 */ public get useDeferredPipeline (): boolean { - return this._useDeferredPipeline; + return this._useDeferredPipeline$; } public get cameraList (): Camera[] { - return this._cameraList; + return this._cameraList$; } /** @@ -245,33 +242,32 @@ export class Root { */ public _createWindowFun: (root: Root) => RenderWindow = null!; - private declare _device: Device; - private _windows: RenderWindow[] = []; - private _mainWindow: RenderWindow | null = null; - private _curWindow: RenderWindow | null = null; - private _tempWindow: RenderWindow | null = null; - private _usesCustomPipeline = true; - private _pipeline: PipelineRuntime | null = null; - private _pipelineEvent: IPipelineEvent | null = new PipelineEventProcessor(); - private _classicPipeline: (PipelineRuntime & IPipelineEvent) | null = null; - private _customPipeline: BasicPipeline | null = null; - private _batcher: Batcher2D | null = null; - private declare _dataPoolMgr: DataPoolManager; - private _scenes: RenderScene[] = []; - private _modelPools = new Map, Pool>(); - private _cameraPool: Pool | null = null; - private _lightPools = new Map, Pool>(); - private _debugView = new DebugView(); - private _fpsTime = 0; - private _frameCount = 0; - private _fps = 0; - private _fixedFPS = 0; - private _useDeferredPipeline = false; - private _fixedFPSFrameTime = 0; - private _cumulativeTime = 0; - private _frameTime = 0; + private declare _device$: Device; + private _windows$: RenderWindow[] = []; + private _mainWindow$: RenderWindow | null = null; + private _curWindow$: RenderWindow | null = null; + private _tempWindow$: RenderWindow | null = null; + private _usesCustomPipeline$ = true; + private _pipeline$: PipelineRuntime | null = null; + private _pipelineEvent$: IPipelineEvent | null = new PipelineEventProcessor(); + private _classicPipeline$: (PipelineRuntime & IPipelineEvent) | null = null; + private _customPipeline$: BasicPipeline | null = null; + private _batcher$: Batcher2D | null = null; + private declare _dataPoolMgr$: DataPoolManager; + private _scenes$: RenderScene[] = []; + private _modelPools$ = new Map, Pool>(); + private _cameraPool$: Pool | null = null; + private _lightPools$ = new Map, Pool>(); + private _debugView$ = new DebugView(); + private _fpsTime$ = 0; + private _frameCount$ = 0; + private _fps$ = 0; + private _fixedFPS$ = 0; + private _useDeferredPipeline$ = false; + private _cumulativeTime$ = 0; + private _frameTime$ = 0; private declare _naitveObj: any; - private _cameraList: Camera[] = []; + private _cameraList$: Camera[] = []; /** * @en The constructor of the root, user shouldn't create the root instance, it's managed by the [[Director]]. @@ -279,13 +275,13 @@ export class Root { * @param device GFX device */ constructor (device: Device) { - this._device = device; - this._dataPoolMgr = cclegacy.internal.DataPoolManager && new cclegacy.internal.DataPoolManager(device) as DataPoolManager; + this._device$ = device; + this._dataPoolMgr$ = cclegacy.internal.DataPoolManager && new cclegacy.internal.DataPoolManager(device) as DataPoolManager; RenderScene.registerCreateFunc(this); RenderWindow.registerCreateFunc(this); - this._cameraPool = new Pool((): Camera => new Camera(this._device), 4, (cam): void => cam.destroy()); + this._cameraPool$ = new Pool((): Camera => new Camera(this._device$), 4, (cam): void => cam.destroy()); } /** @@ -303,19 +299,19 @@ export class Root { depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD; const renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment); - this._mainWindow = this.createWindow({ + this._mainWindow$ = this.createWindow({ title: 'rootMainWindow', width: swapchain.width, height: swapchain.height, renderPassInfo, swapchain, }); - this._curWindow = this._mainWindow; + this._curWindow$ = this._mainWindow$; const customJointTextureLayouts = settings.querySettings( - Settings.Category.ANIMATION, + SettingsCategory.ANIMATION, 'customJointTextureLayouts', ) as ICustomJointTextureLayout[] || []; - this._dataPoolMgr?.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts); + this._dataPoolMgr$?.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts); this._resizeMaxJointForDS(); } @@ -326,19 +322,19 @@ export class Root { public destroy (): void { this.destroyScenes(); - if (this._pipeline) { - this._pipeline.destroy(); - this._pipeline = null; - this._pipelineEvent = null; + if (this._pipeline$) { + this._pipeline$.destroy(); + this._pipeline$ = null; + this._pipelineEvent$ = null; } - if (this._batcher) { - this._batcher.destroy(); - this._batcher = null; + if (this._batcher$) { + this._batcher$.destroy(); + this._batcher$ = null; } - this._curWindow = null; - this._mainWindow = null; + this._curWindow$ = null; + this._mainWindow$ = null; this.dataPoolManager.clear(); if (cclegacy.rendering) { @@ -354,7 +350,7 @@ export class Root { * @param windowId The system window ID, optional for now. */ public resize (width: number, height: number, windowId?: number): void { - for (const window of this._windows) { + for (const window of this._windows$) { if (window.swapchain) { window.resize(width, height); } @@ -378,9 +374,9 @@ export class Root { //----------------------------------------------- let isCreateDefaultPipeline = false; if (useCustomPipeline) { - this._customPipeline = rendering.createCustomPipeline(); + this._customPipeline$ = rendering.createCustomPipeline(); isCreateDefaultPipeline = true; - this._pipeline = this._customPipeline!; + this._pipeline$ = this._customPipeline$!; // Use default _pipelineEvent log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`); } else { @@ -388,22 +384,22 @@ export class Root { isCreateDefaultPipeline = true; log(`Using legacy pipeline`); - this._classicPipeline = rppl!; - this._pipeline = this._classicPipeline; - this._pipelineEvent = this._classicPipeline; // Use forward pipeline's pipeline event - this._usesCustomPipeline = false; + this._classicPipeline$ = rppl!; + this._pipeline$ = this._classicPipeline$; + this._pipelineEvent$ = this._classicPipeline$; // Use forward pipeline's pipeline event + this._usesCustomPipeline$ = false; } - const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode'); - if (renderMode !== LegacyRenderMode.HEADLESS || this._classicPipeline) { - if (!this._pipeline.activate(this._mainWindow!.swapchain)) { + const renderMode = settings.querySettings(SettingsCategory.RENDERING, 'renderMode'); + if (renderMode !== LegacyRenderMode.HEADLESS || this._classicPipeline$) { + if (!this._pipeline$.activate(this._mainWindow$!.swapchain)) { if (isCreateDefaultPipeline) { - this._pipeline.destroy(); + this._pipeline$.destroy(); } - this._classicPipeline = null; - this._customPipeline = null; - this._pipeline = null; - this._pipelineEvent = null; + this._classicPipeline$ = null; + this._customPipeline$ = null; + this._pipeline$ = null; + this._pipelineEvent$ = null; return false; } @@ -418,9 +414,9 @@ export class Root { } this.onGlobalPipelineStateChanged(); - if (!this._batcher && internal.Batcher2D) { - this._batcher = new internal.Batcher2D(this); - if (!this._batcher!.initialize()) { + if (!this._batcher$ && internal.Batcher2D) { + this._batcher$ = new internal.Batcher2D(this); + if (!this._batcher$!.initialize()) { this.destroy(); return false; } @@ -434,15 +430,15 @@ export class Root { * @zh 通知渲染管线和所有场景全局管线状态已更新,需要更新自身状态。 */ public onGlobalPipelineStateChanged (): void { - for (let i = 0; i < this._scenes.length; i++) { - this._scenes[i].onGlobalPipelineStateChanged(); + for (let i = 0; i < this._scenes$.length; i++) { + this._scenes$[i].onGlobalPipelineStateChanged(); } - if (this._pipeline!.pipelineSceneData.skybox.enabled) { - this._pipeline!.pipelineSceneData.skybox.model!.onGlobalPipelineStateChanged(); + if (this._pipeline$!.pipelineSceneData.skybox.enabled) { + this._pipeline$!.pipelineSceneData.skybox.model!.onGlobalPipelineStateChanged(); } - this._pipeline!.onGlobalPipelineStateChanged(); + this._pipeline$!.onGlobalPipelineStateChanged(); } /** @@ -451,7 +447,7 @@ export class Root { * @param window The render window to be activated */ public activeWindow (window: RenderWindow): void { - this._curWindow = window; + this._curWindow$ = window; } /** @@ -459,7 +455,7 @@ export class Root { * @zh 重置累计时间 */ public resetCumulativeTime (): void { - this._cumulativeTime = 0; + this._cumulativeTime$ = 0; } /** @@ -468,26 +464,15 @@ export class Root { * @param deltaTime @en The delta time since last update. @zh 距离上一帧间隔时间 */ public frameMove (deltaTime: number): void { - this._frameTime = deltaTime; - - /* - if (this._fixedFPSFrameTime > 0) { - - const elapsed = this._frameTime * 1000.0; - if (this._fixedFPSFrameTime > elapsed) { - - setTimeout(function () {}, this._fixedFPSFrameTime - elapsed); - } - } - */ - - ++this._frameCount; - this._cumulativeTime += deltaTime; - this._fpsTime += deltaTime; - if (this._fpsTime > 1.0) { - this._fps = this._frameCount; - this._frameCount = 0; - this._fpsTime = 0.0; + this._frameTime$ = deltaTime; + + ++this._frameCount$; + this._cumulativeTime$ += deltaTime; + this._fpsTime$ += deltaTime; + if (this._fpsTime$ > 1.0) { + this._fps$ = this._frameCount$; + this._frameCount$ = 0; + this._fpsTime$ = 0.0; } if (globalThis.__globalXR?.isWebXR) { @@ -507,7 +492,7 @@ export class Root { public createWindow (info: IRenderWindowInfo): RenderWindow | null { const window = this._createWindowFun(this); window.initialize(this.device, info); - this._windows.push(window); + this._windows$.push(window); return window; } @@ -517,10 +502,10 @@ export class Root { * @param window The render window to be destroyed */ public destroyWindow (window: RenderWindow): void { - for (let i = 0; i < this._windows.length; ++i) { - if (this._windows[i] === window) { + for (let i = 0; i < this._windows$.length; ++i) { + if (this._windows$[i] === window) { window.destroy(); - this._windows.splice(i, 1); + this._windows$.splice(i, 1); return; } } @@ -531,10 +516,10 @@ export class Root { * @zh 销毁全部窗口 */ public destroyWindows (): void { - for (const window of this._windows) { + for (const window of this._windows$) { window.destroy(); } - this._windows.length = 0; + this._windows$.length = 0; } /** @@ -545,7 +530,7 @@ export class Root { public createScene (info: IRenderSceneInfo): RenderScene { const scene: RenderScene = this._createSceneFun(this); scene.initialize(info); - this._scenes.push(scene); + this._scenes$.push(scene); return scene; } @@ -555,10 +540,10 @@ export class Root { * @param scene @en The render scene to be destroyed. @zh 要销毁的渲染场景 */ public destroyScene (scene: RenderScene): void { - for (let i = 0; i < this._scenes.length; ++i) { - if (this._scenes[i] === scene) { + for (let i = 0; i < this._scenes$.length; ++i) { + if (this._scenes$[i] === scene) { scene.destroy(); - this._scenes.splice(i, 1); + this._scenes$.splice(i, 1); return; } } @@ -569,10 +554,10 @@ export class Root { * @zh 销毁全部场景。 */ public destroyScenes (): void { - for (const scene of this._scenes) { + for (const scene of this._scenes$) { scene.destroy(); } - this._scenes.length = 0; + this._scenes$.length = 0; } /** @@ -582,10 +567,10 @@ export class Root { * @returns The model created */ public createModel (ModelCtor: typeof Model): T { - let p = this._modelPools.get(ModelCtor); + let p = this._modelPools$.get(ModelCtor); if (!p) { - this._modelPools.set(ModelCtor, new Pool((): Model => new ModelCtor(), 10, (obj): void => obj.destroy())); - p = this._modelPools.get(ModelCtor)!; + this._modelPools$.set(ModelCtor, new Pool((): Model => new ModelCtor(), 10, (obj): void => obj.destroy())); + p = this._modelPools$.get(ModelCtor)!; } const model = p.alloc() as T; model.initialize(); @@ -598,7 +583,7 @@ export class Root { * @param m @en The model to be destroyed @zh 要销毁的模型 */ public destroyModel (m: Model): void { - const p = this._modelPools.get(m.constructor as Constructor); + const p = this._modelPools$.get(m.constructor as Constructor); if (p) { p.free(m); if (m.scene) { @@ -616,7 +601,7 @@ export class Root { * @returns The camera created. */ public createCamera (): Camera { - return this._cameraPool!.alloc(); + return this._cameraPool$!.alloc(); } /** @@ -626,10 +611,10 @@ export class Root { * @returns The light created */ public createLight (LightCtor: new () => T): T { - let l = this._lightPools.get(LightCtor); + let l = this._lightPools$.get(LightCtor); if (!l) { - this._lightPools.set(LightCtor, new Pool((): T => new LightCtor(), 4, (obj): void => obj.destroy())); - l = this._lightPools.get(LightCtor)!; + this._lightPools$.set(LightCtor, new Pool((): T => new LightCtor(), 4, (obj): void => obj.destroy())); + l = this._lightPools$.get(LightCtor)!; } const light = l.alloc() as T; light.initialize(); @@ -672,7 +657,7 @@ export class Root { * @param l @en The light to be recycled @zh 要回收的光源 */ public recycleLight (l: Light): void { - const p = this._lightPools.get(l.constructor as Constructor); + const p = this._lightPools$.get(l.constructor as Constructor); if (p) { p.free(l); if (l.scene) { @@ -705,8 +690,8 @@ export class Root { return; } - const windows = this._windows; - const cameraList = this._cameraList; + const windows = this._windows$; + const cameraList = this._cameraList$; const viewCount = xr.webXRMatProjs ? xr.webXRMatProjs.length : 1; if (!xr.webXRWindowMap) { xr.webXRWindowMap = new Map(); @@ -766,31 +751,31 @@ export class Root { } private _frameMoveBegin (): void { - for (let i = 0; i < this._scenes.length; ++i) { - this._scenes[i].removeBatches(); + for (let i = 0; i < this._scenes$.length; ++i) { + this._scenes$[i].removeBatches(); } - this._cameraList.length = 0; + this._cameraList$.length = 0; } private _frameMoveProcess (): void { const { director } = cclegacy; - const windows = this._windows; - const cameraList = this._cameraList; + const windows = this._windows$; + const cameraList = this._cameraList$; for (let i = 0; i < windows.length; i++) { const window = windows[i]; window.extractRenderCameras(cameraList); } - if (this._pipeline && cameraList.length > 0) { - this._device.acquire([deviceManager.swapchain]); - const scenes = this._scenes; + if (this._pipeline$ && cameraList.length > 0) { + this._device$.acquire([deviceManager.swapchain]); + const scenes = this._scenes$; const stamp = director.getTotalFrames() as number; - if (this._batcher) { - this._batcher.update(); - this._batcher.uploadBuffers(); + if (this._batcher$) { + this._batcher$.update(); + this._batcher$.uploadBuffers(); } for (let i = 0; i < scenes.length; i++) { @@ -801,8 +786,8 @@ export class Root { private _frameMoveEnd (): void { const { director, Director } = cclegacy; - const cameraList = this._cameraList; - if (this._pipeline && cameraList.length > 0) { + const cameraList = this._cameraList$; + if (this._pipeline$ && cameraList.length > 0) { director.emit(Director.EVENT_BEFORE_COMMIT); cameraList.sort((a: Camera, b: Camera): number => a.priority - b.priority); @@ -810,17 +795,17 @@ export class Root { cameraList[i].geometryRenderer?.update(); } director.emit(Director.EVENT_BEFORE_RENDER); - this._pipeline.render(cameraList); + this._pipeline$.render(cameraList); director.emit(Director.EVENT_AFTER_RENDER); - this._device.present(); + this._device$.present(); } - if (this._batcher) this._batcher.reset(); + if (this._batcher$) this._batcher$.reset(); } private _resizeMaxJointForDS (): void { // TODO: usedUBOVectorCount should be estimated more carefully, the UBOs used could vary in different scenes. - const usedUBOVectorCount = Math.max((UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOLocal.COUNT + UBOWorldBound.COUNT) / 4, 100); + const usedUBOVectorCount = Math.max((UBOGlobalEnum.COUNT + UBOCameraEnum.COUNT + UBOShadowEnum.COUNT + UBOLocalEnum.COUNT + UBOWorldBound.COUNT) / 4, 100); let maxJoints = Math.floor((deviceManager.gfxDevice.capabilities.maxVertexUniformVectors - usedUBOVectorCount) / 3); maxJoints = maxJoints < 256 ? maxJoints : 256; localDescriptorSetLayout_ResizeMaxJoints(maxJoints); diff --git a/cocos/scene-graph/layers.ts b/cocos/scene-graph/layers.ts index c1133e557df..275140ace4d 100644 --- a/cocos/scene-graph/layers.ts +++ b/cocos/scene-graph/layers.ts @@ -28,7 +28,7 @@ import { log2 } from '../core/math/bits'; import { js } from '../core'; import { assertIsTrue } from '../core/data/utils/asserts'; import { getError, warnID } from '../core/platform/debug'; -import { Settings, settings } from '../core/settings'; +import { settings, SettingsCategory } from '../core/settings'; // built-in layers, users can use 0~19 bits, 20~31 are system preserve bits. const layerList = { @@ -74,7 +74,7 @@ export class Layers { * @internal */ public static init (): void { - const userLayers = settings.querySettings(Settings.Category.ENGINE, 'customLayers'); + const userLayers = settings.querySettings(SettingsCategory.ENGINE, 'customLayers'); if (!userLayers) return; for (let i = 0; i < userLayers.length; i++) { const layer = userLayers[i]; diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts index da4c3875535..edff9d248f6 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/scene-graph/node-event-processor.ts @@ -157,7 +157,7 @@ export class NodeEventProcessor { const node = this.node; const children = node.children; if (value) { - this._attachMask(); + this._attachMask$(); } NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY); if (recursive && children.length > 0) { @@ -196,26 +196,26 @@ export class NodeEventProcessor { } public on (type: NodeEventType, callback: AnyFunction, target?: unknown, useCapture?: boolean): AnyFunction { - this._tryEmittingAddEvent(type); + this._tryEmittingAddEvent$(type); useCapture = !!useCapture; let invoker: CallbacksInvoker; if (useCapture) { - invoker = this.capturingTarget ??= this._newCallbacksInvoker(); + invoker = this.capturingTarget ??= this._newCallbacksInvoker$(); } else { - invoker = this.bubblingTarget ??= this._newCallbacksInvoker(); + invoker = this.bubblingTarget ??= this._newCallbacksInvoker$(); } invoker.on(type, callback, target); return callback; } public once (type: NodeEventType, callback: AnyFunction, target?: unknown, useCapture?: boolean): AnyFunction { - this._tryEmittingAddEvent(type); + this._tryEmittingAddEvent$(type); useCapture = !!useCapture; let invoker: CallbacksInvoker; if (useCapture) { - invoker = this.capturingTarget ??= this._newCallbacksInvoker(); + invoker = this.capturingTarget ??= this._newCallbacksInvoker$(); } else { - invoker = this.bubblingTarget ??= this._newCallbacksInvoker(); + invoker = this.bubblingTarget ??= this._newCallbacksInvoker$(); } invoker.on(type, callback, target, true); @@ -238,13 +238,13 @@ export class NodeEventProcessor { this.bubblingTarget?.removeAll(target); // emit event - if (this.shouldHandleEventTouch && !this._hasTouchListeners()) { + if (this.shouldHandleEventTouch && !this._hasTouchListeners$()) { this.shouldHandleEventTouch = false; } - if (this.shouldHandleEventMouse && !this._hasMouseListeners()) { + if (this.shouldHandleEventMouse && !this._hasMouseListeners$()) { this.shouldHandleEventMouse = false; } - if (!this._hasPointerListeners()) { + if (!this._hasPointerListeners$()) { NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this); } } @@ -394,21 +394,21 @@ export class NodeEventProcessor { return null; } - private _attachMask (): void { + private _attachMask$ (): void { this.maskList = this._searchComponentsInParent(NodeEventProcessor._maskComp); } - private _isTouchEvent (type: NodeEventType): boolean { + private _isTouchEvent$ (type: NodeEventType): boolean { const index = _touchEvents.indexOf(type); return index !== -1; } - private _isMouseEvent (type: NodeEventType): boolean { + private _isMouseEvent$ (type: NodeEventType): boolean { const index = _mouseEvents.indexOf(type); return index !== -1; } - private _hasTouchListeners (): boolean { + private _hasTouchListeners$ (): boolean { for (let i = 0; i < _touchEvents.length; ++i) { const eventType = _touchEvents[i]; if (this.hasEventListener(eventType)) { @@ -418,7 +418,7 @@ export class NodeEventProcessor { return false; } - private _hasMouseListeners (): boolean { + private _hasMouseListeners$ (): boolean { for (let i = 0; i < _mouseEvents.length; ++i) { const eventType = _mouseEvents[i]; if (this.hasEventListener(eventType)) { @@ -428,23 +428,23 @@ export class NodeEventProcessor { return false; } - private _hasPointerListeners (): boolean { - const has = this._hasTouchListeners(); + private _hasPointerListeners$ (): boolean { + const has = this._hasTouchListeners$(); if (has) { return true; } - return this._hasMouseListeners(); + return this._hasMouseListeners$(); } - private _tryEmittingAddEvent (typeToAdd: NodeEventType): void { - const isTouchEvent = this._isTouchEvent(typeToAdd); - const isMouseEvent = this._isMouseEvent(typeToAdd); + private _tryEmittingAddEvent$ (typeToAdd: NodeEventType): void { + const isTouchEvent = this._isTouchEvent$(typeToAdd); + const isMouseEvent = this._isMouseEvent$(typeToAdd); if (isTouchEvent) { this.shouldHandleEventTouch = true; } else if (isMouseEvent) { this.shouldHandleEventMouse = true; } - if ((isTouchEvent || isMouseEvent) && !this._hasPointerListeners()) { + if ((isTouchEvent || isMouseEvent) && !this._hasPointerListeners$()) { NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.ADD_POINTER_EVENT_PROCESSOR, this); } } @@ -454,16 +454,16 @@ export class NodeEventProcessor { * We need to inject some nodeEventProcessor's logic into the `callbacksInvoker.off` method. * @returns {CallbacksInvoker} decorated callbacks invoker */ - private _newCallbacksInvoker (): CallbacksInvoker { + private _newCallbacksInvoker$ (): CallbacksInvoker { const callbacksInvoker = new CallbacksInvoker(); callbacksInvoker._registerOffCallback(() => { - if (this.shouldHandleEventTouch && !this._hasTouchListeners()) { + if (this.shouldHandleEventTouch && !this._hasTouchListeners$()) { this.shouldHandleEventTouch = false; } - if (this.shouldHandleEventMouse && !this._hasMouseListeners()) { + if (this.shouldHandleEventMouse && !this._hasMouseListeners$()) { this.shouldHandleEventMouse = false; } - if (!this._hasPointerListeners()) { + if (!this._hasPointerListeners$()) { NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this); } }); @@ -478,23 +478,23 @@ export class NodeEventProcessor { public _handleEventMouse (eventMouse: EventMouse): boolean { switch (eventMouse.type) { case InputEventType.MOUSE_DOWN: - return this._handleMouseDown(eventMouse); + return this._handleMouseDown$(eventMouse); case InputEventType.MOUSE_MOVE: - return this._handleMouseMove(eventMouse); + return this._handleMouseMove$(eventMouse); case InputEventType.MOUSE_UP: - return this._handleMouseUp(eventMouse); + return this._handleMouseUp$(eventMouse); case InputEventType.MOUSE_WHEEL: - return this._handleMouseWheel(eventMouse); + return this._handleMouseWheel$(eventMouse); case InputEventType.MOUSE_LEAVE: - return this._handleMouseLeave(eventMouse); + return this._handleMouseLeave$(eventMouse); case InputEventType.MOUSE_ENTER: - return this._handleMouseEnter(eventMouse); + return this._handleMouseEnter$(eventMouse); default: return false; } } - private _handleMouseDown (event: EventMouse): boolean { + private _handleMouseDown$ (event: EventMouse): boolean { const node = this._node; if (!node || !node._uiProps.uiTransformComp) { return false; @@ -512,7 +512,7 @@ export class NodeEventProcessor { return false; } - private _handleMouseMove (event: EventMouse): boolean { + private _handleMouseMove$ (event: EventMouse): boolean { const node = this._node; if (!node || !node._uiProps.uiTransformComp || this._isMouseLeaveWindow) { return false; @@ -548,7 +548,7 @@ export class NodeEventProcessor { return false; } - private _handleMouseUp (event: EventMouse): boolean { + private _handleMouseUp$ (event: EventMouse): boolean { const node = this._node; if (!node || !node._uiProps.uiTransformComp) { return false; @@ -566,7 +566,7 @@ export class NodeEventProcessor { return false; } - private _handleMouseWheel (event: EventMouse): boolean { + private _handleMouseWheel$ (event: EventMouse): boolean { const node = this._node; if (!node || !node._uiProps.uiTransformComp) { return false; @@ -585,7 +585,7 @@ export class NodeEventProcessor { return false; } - private _handleMouseLeave (event: EventMouse): boolean { + private _handleMouseLeave$ (event: EventMouse): boolean { this._isMouseLeaveWindow = true; if (this.previousMouseIn) { event.type = NodeEventType.MOUSE_LEAVE; @@ -596,7 +596,7 @@ export class NodeEventProcessor { return false; } - private _handleMouseEnter (event: EventMouse): boolean { + private _handleMouseEnter$ (event: EventMouse): boolean { this._isMouseLeaveWindow = false; return false; } @@ -612,13 +612,13 @@ export class NodeEventProcessor { try { switch (eventTouch.type) { case InputEventType.TOUCH_START: - return this._handleTouchStart(eventTouch); + return this._handleTouchStart$(eventTouch); case InputEventType.TOUCH_MOVE: - return this._handleTouchMove(eventTouch); + return this._handleTouchMove$(eventTouch); case InputEventType.TOUCH_END: - return this._handleTouchEnd(eventTouch); + return this._handleTouchEnd$(eventTouch); case InputEventType.TOUCH_CANCEL: - return this._handleTouchCancel(eventTouch); + return this._handleTouchCancel$(eventTouch); default: return false; } @@ -628,7 +628,7 @@ export class NodeEventProcessor { } } - private _handleTouchStart (event: EventTouch): boolean { + private _handleTouchStart$ (event: EventTouch): boolean { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return false; @@ -647,7 +647,7 @@ export class NodeEventProcessor { return false; } - private _handleTouchMove (event: EventTouch): boolean { + private _handleTouchMove$ (event: EventTouch): boolean { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return false; @@ -660,7 +660,7 @@ export class NodeEventProcessor { return true; } - private _handleTouchEnd (event: EventTouch): void { + private _handleTouchEnd$ (event: EventTouch): void { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return; @@ -678,7 +678,7 @@ export class NodeEventProcessor { this._dispatchingTouch = null; } - private _handleTouchCancel (event: EventTouch): void { + private _handleTouchCancel$ (event: EventTouch): void { const node = this.node; if (!node || !node._uiProps.uiTransformComp) { return; diff --git a/cocos/scene-graph/node-ui-properties.ts b/cocos/scene-graph/node-ui-properties.ts index d620f173df1..4b4f0f4d1a6 100644 --- a/cocos/scene-graph/node-ui-properties.ts +++ b/cocos/scene-graph/node-ui-properties.ts @@ -39,7 +39,7 @@ export class NodeUIProperties { */ get uiTransformComp (): UITransform | null { if (!this._uiTransformComp) { - this._uiTransformComp = this._node.getComponent('cc.UITransform') as UITransform; + this._uiTransformComp = this._node$.getComponent('cc.UITransform') as UITransform; } return this._uiTransformComp; @@ -53,54 +53,54 @@ export class NodeUIProperties { * @zh UI 基类组件 */ get uiComp (): UIMeshRenderer | UIRenderer | null { - return this._uiComp; + return this._uiComp$; } set uiComp (comp: UIMeshRenderer | UIRenderer | null) { - if (this._uiComp && comp) { + if (this._uiComp$ && comp) { warnID(12002); return; } - this._uiComp = comp; + this._uiComp$ = comp; } - private _uiComp: UIMeshRenderer | UIRenderer | null = null; + private _uiComp$: UIMeshRenderer | UIRenderer | null = null; /** * @en The opacity of the UI node for final rendering * @zh 最终显示的 UI 透明度,受父节点透明度影响 */ - private _opacity = 1; + private _opacity$ = 1; /** * NOTE: engineInternal tag cannot only mark opacity setter as internal. * @engineInternal */ - public setOpacity (v: number): void { this._opacity = v; } - public get opacity (): number { return this._opacity; } + public setOpacity (v: number): void { this._opacity$ = v; } + public get opacity (): number { return this._opacity$; } /** * @en The opacity of the UI node itself * @zh 本节点的 UI 透明度 */ - private _localOpacity = 1; - get localOpacity (): number { return this._localOpacity; } + private _localOpacity$ = 1; + get localOpacity (): number { return this._localOpacity$; } set localOpacity (val) { - this._localOpacity = val; + this._localOpacity$ = val; this.colorDirty = true; } public colorDirty = true; protected _uiTransformComp: UITransform | null = null; - private declare _node: Node; + private declare _node$: Node; constructor (node: Node) { - this._node = node; + this._node$ = node; } /** * @deprecated since v3.4 */ public applyOpacity (effectOpacity: number): void { - this._opacity = this._localOpacity * effectOpacity; + this._opacity$ = this._localOpacity$ * effectOpacity; } /** diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 9f10a77baa0..8e5430c8977 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -1495,8 +1495,8 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * @en Counter to clear node array * @zh 清除节点数组计时器 */ - private static ClearFrame = 0; - private static ClearRound = 1000; + private static ClearFrame$ = 0; + private static ClearRound$ = 1000; /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. @@ -2759,10 +2759,10 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { * 清除节点数组 */ public static clearNodeArray (): void { - if (Node.ClearFrame < Node.ClearRound && !EDITOR) { - Node.ClearFrame++; + if (Node.ClearFrame$ < Node.ClearRound$ && !EDITOR) { + Node.ClearFrame$++; } else { - Node.ClearFrame = 0; + Node.ClearFrame$ = 0; dirtyNodes.length = 0; } } diff --git a/cocos/scene-graph/prefab/prefab.ts b/cocos/scene-graph/prefab/prefab.ts index e1ad1e78251..1dff1520633 100644 --- a/cocos/scene-graph/prefab/prefab.ts +++ b/cocos/scene-graph/prefab/prefab.ts @@ -112,8 +112,8 @@ export class Prefab extends Asset { public persistent = false; // Cache function to optimize instance creation. - private _createFunction: ((...arg: any[]) => Node) | null = null; - private _instantiatedTimes: number = 0; + private _createFunction$: ((...arg: any[]) => Node) | null = null; + private _instantiatedTimes$: number = 0; constructor () { super(); } @@ -135,7 +135,9 @@ export class Prefab extends Asset { * 但是您可以在脚本中修改原始预制数据后重新调用以刷新创建功能。 */ public compileCreateFunction (): void { - this._createFunction = compile(this.data); + if (SUPPORT_JIT) { + this._createFunction$ = compile(this.data); + } } // just instantiate, will not initialize the Node, this will be called during Node's initialization. @@ -149,10 +151,10 @@ export class Prefab extends Asset { // temp guard code warnID(3700); } - if (!this._createFunction) { + if (!this._createFunction$) { this.compileCreateFunction(); } - return this._createFunction!(rootToRedirect); // this.data._instantiate(); + return this._createFunction$!(rootToRedirect); // this.data._instantiate(); } private _instantiate (): Node { @@ -165,7 +167,7 @@ export class Prefab extends Asset { useJit = true; } else { // auto - useJit = (this._instantiatedTimes + 1) >= Prefab.OptimizationPolicyThreshold; + useJit = (this._instantiatedTimes$ + 1) >= Prefab.OptimizationPolicyThreshold; } } if (useJit) { @@ -177,7 +179,7 @@ export class Prefab extends Asset { // instantiate node node = this.data._instantiate(); } - ++this._instantiatedTimes; + ++this._instantiatedTimes$; return node; } diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index 08ef6ee8484..577f671963b 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -44,7 +44,6 @@ import { Material, MaterialPropertyFull } from '../asset/assets/material'; import { cclegacy, macro } from '../core'; import { Scene } from './scene'; import { NodeEventType } from './node-event'; -import { property } from '../core/data/class-decorator'; import { PostSettings, ToneMappingType } from '../render-scene/scene/post-settings'; const _up = new Vec3(0, 1, 0); @@ -1439,15 +1438,15 @@ export class LightProbeInfo { } public onProbeBakeFinished (): void { - this.onProbeBakingChanged(this._scene); + this.onProbeBakingChanged$(this._scene); } public onProbeBakeCleared (): void { this.clearSHCoefficients(); - this.onProbeBakingChanged(this._scene); + this.onProbeBakingChanged$(this._scene); } - private onProbeBakingChanged (node: Node | null): void { + private onProbeBakingChanged$ (node: Node | null): void { if (!node) { return; } @@ -1456,7 +1455,7 @@ export class LightProbeInfo { for (let i = 0; i < node.children.length; i++) { const child = node.children[i]; - this.onProbeBakingChanged(child); + this.onProbeBakingChanged$(child); } } @@ -1470,7 +1469,7 @@ export class LightProbeInfo { probes[i].coefficients.length = 0; } - this.clearAllSHUBOs(); + this.clearAllSHUBOs$(); } public isUniqueNode (): boolean { @@ -1548,7 +1547,7 @@ export class LightProbeInfo { const pointCount = points.length; if (pointCount < 4) { - this.resetAllTetraIndices(); + this.resetAllTetraIndices$(); this._data!.reset(); return; } @@ -1556,12 +1555,12 @@ export class LightProbeInfo { this._data!.updateProbes(points); if (updateTet) { - this.resetAllTetraIndices(); + this.resetAllTetraIndices$(); this._data!.updateTetrahedrons(); } } - private clearAllSHUBOs (): void { + private clearAllSHUBOs$ (): void { if (!this._scene) { return; } @@ -1577,7 +1576,7 @@ export class LightProbeInfo { } } - private resetAllTetraIndices (): void { + private resetAllTetraIndices$ (): void { if (!this._scene) { return; } diff --git a/cocos/serialization/ccon.ts b/cocos/serialization/ccon.ts index 8d30642bd1e..30656b84555 100644 --- a/cocos/serialization/ccon.ts +++ b/cocos/serialization/ccon.ts @@ -32,20 +32,20 @@ const CHUNK_ALIGN_AS = 8; export class CCON { constructor (document: unknown, chunks: Uint8Array[]) { - this._document = document; - this._chunks = chunks; + this._document$ = document; + this._chunks$ = chunks; } get document (): unknown { - return this._document; + return this._document$; } get chunks (): Uint8Array[] { - return this._chunks; + return this._chunks$; } - private declare _document: unknown; - private declare _chunks: Uint8Array[]; + private declare _document$: unknown; + private declare _chunks$: Uint8Array[]; } interface CCONPreface { @@ -214,20 +214,20 @@ function decodeJson (data: Uint8Array): string { export class InvalidCCONError extends Error { } export class BufferBuilder { - private _viewOrPaddings: (ArrayBufferView | number)[] = []; - private _length = 0; + private _viewOrPaddings$: (ArrayBufferView | number)[] = []; + private _length$ = 0; get byteLength (): number { - return this._length; + return this._length$; } public alignAs (align: number): number { if (align !== 0) { - const remainder = this._length % align; + const remainder = this._length$ % align; if (remainder !== 0) { const padding = align - remainder; - this._viewOrPaddings.push(padding); - this._length += padding; + this._viewOrPaddings$.push(padding); + this._length$ += padding; return padding; } } @@ -235,16 +235,16 @@ export class BufferBuilder { } public append (view: ArrayBufferView): number { - const result = this._length; - this._viewOrPaddings.push(view); - this._length += view.byteLength; + const result = this._length$; + this._viewOrPaddings$.push(view); + this._length$ += view.byteLength; return result; } public get (): Uint8Array { - const result = new Uint8Array(this._length); + const result = new Uint8Array(this._length$); let counter = 0; - this._viewOrPaddings.forEach((viewOrPadding) => { + this._viewOrPaddings$.forEach((viewOrPadding) => { if (typeof viewOrPadding === 'number') { counter += viewOrPadding; } else { diff --git a/cocos/serialization/deserialize-dynamic.ts b/cocos/serialization/deserialize-dynamic.ts index 7e0d8a9fced..b93959a67dc 100644 --- a/cocos/serialization/deserialize-dynamic.ts +++ b/cocos/serialization/deserialize-dynamic.ts @@ -385,37 +385,37 @@ class _Deserializer { public declare customEnv: unknown; public deserializedList: Array | undefined> = []; public deserializedData: any = null; - private declare _classFinder: ClassFinder; - private declare _reportMissingClass: ReportMissingClass; - private declare _onDereferenced: ClassFinder['onDereferenced']; + private declare _classFinder$: ClassFinder; + private declare _reportMissingClass$: ReportMissingClass; + private declare _onDereferenced$: ClassFinder['onDereferenced']; /** * @engineInternal */ - public get ignoreEditorOnly (): unknown { return this._ignoreEditorOnly; } - private declare _ignoreEditorOnly: unknown; - private declare _mainBinChunk: Uint8Array; - private declare _serializedData: SerializedObject | SerializedObject[]; - private declare _context: DeserializationContext; + public get ignoreEditorOnly (): unknown { return this._ignoreEditorOnly$; } + private declare _ignoreEditorOnly$: unknown; + private declare _mainBinChunk$: Uint8Array; + private declare _serializedData$: SerializedObject | SerializedObject[]; + private declare _context$: DeserializationContext; constructor (result: Details, classFinder: ClassFinder, reportMissingClass: ReportMissingClass, customEnv: unknown, ignoreEditorOnly: unknown) { this.result = result; this.customEnv = customEnv; - this._classFinder = classFinder; - this._reportMissingClass = reportMissingClass; - this._onDereferenced = classFinder?.onDereferenced; + this._classFinder$ = classFinder; + this._reportMissingClass$ = reportMissingClass; + this._onDereferenced$ = classFinder?.onDereferenced; if (DEV) { - this._ignoreEditorOnly = ignoreEditorOnly; + this._ignoreEditorOnly$ = ignoreEditorOnly; } } public reset (result: Details, classFinder: ClassFinder, reportMissingClass: ReportMissingClass, customEnv: unknown, ignoreEditorOnly: unknown): void { this.result = result; this.customEnv = customEnv; - this._classFinder = classFinder; - this._reportMissingClass = reportMissingClass; - this._onDereferenced = classFinder?.onDereferenced; + this._classFinder$ = classFinder; + this._reportMissingClass$ = reportMissingClass; + this._onDereferenced$ = classFinder?.onDereferenced; if (DEV) { - this._ignoreEditorOnly = ignoreEditorOnly; + this._ignoreEditorOnly$ = ignoreEditorOnly; } } @@ -424,9 +424,9 @@ class _Deserializer { this.customEnv = null; this.deserializedList.length = 0; this.deserializedData = null; - this._classFinder = null!; - this._reportMissingClass = null!; - this._onDereferenced = null!; + this._classFinder$ = null!; + this._reportMissingClass$ = null!; + this._onDereferenced$ = null!; } public deserialize (serializedData: SerializedData | CCON): any { @@ -437,28 +437,28 @@ class _Deserializer { jsonObj = serializedData.document as SerializedData; if (serializedData.chunks.length > 0) { assertIsTrue(serializedData.chunks.length === 1); - this._mainBinChunk = serializedData.chunks[0]; + this._mainBinChunk$ = serializedData.chunks[0]; } } else { jsonObj = serializedData; } - this._serializedData = jsonObj; - this._context = { + this._serializedData$ = jsonObj; + this._context$ = { fromCCON, }; const serializedRootObject = Array.isArray(jsonObj) ? jsonObj[0] : jsonObj; if (EDITOR || TEST) { - this.deserializedData = this._deserializeObject(serializedRootObject, 0, this.deserializedList, `${0}`); + this.deserializedData = this._deserializeObject$(serializedRootObject, 0, this.deserializedList, `${0}`); } else { - this.deserializedData = this._deserializeObject(serializedRootObject, 0); + this.deserializedData = this._deserializeObject$(serializedRootObject, 0); } - this._serializedData = undefined!; - this._mainBinChunk = undefined!; - this._context = undefined!; + this._serializedData$ = undefined!; + this._mainBinChunk$ = undefined!; + this._context$ = undefined!; // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this.deserializedData; @@ -470,7 +470,7 @@ class _Deserializer { * @param owner - Tracing purpose. * @param propName - Tracing purpose. */ - private _deserializeObject ( + private _deserializeObject$ ( serialized: SerializedObject, globalIndex: number, owner?: Record | unknown[], @@ -478,36 +478,36 @@ class _Deserializer { ): Record | null { switch (serialized.__type__) { case 'TypedArray': - return this._deserializeTypedArrayView(serialized); + return this._deserializeTypedArrayView$(serialized); case 'TypedArrayRef': - return this._deserializeTypedArrayViewRef(serialized); + return this._deserializeTypedArrayViewRef$(serialized); default: // NOTE: when 'strictNullCheck' is false, TS can't infer serialized as SerializedGeneralTypedObject if ((serialized as unknown as SerializedGeneralTypedObject).__type__) { // Typed object (including CCClass) - return this._deserializeTypeTaggedObject(serialized, globalIndex, owner, propName); + return this._deserializeTypeTaggedObject$(serialized, globalIndex, owner, propName); } else if (!Array.isArray(serialized)) { // Embedded primitive javascript object - return this._deserializePlainObject(serialized); + return this._deserializePlainObject$(serialized); } else { // Array - return this._deserializeArray(serialized); + return this._deserializeArray$(serialized); } } } - private _deserializeTypedArrayView (value: SerializedTypedArray): Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array { + private _deserializeTypedArrayView$ (value: SerializedTypedArray): Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array { return globalThis[value.ctor].from(value.array); } - private _deserializeTypedArrayViewRef (value: SerializedTypedArrayRef): Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array { + private _deserializeTypedArrayViewRef$ (value: SerializedTypedArrayRef): Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array { const { offset, length, ctor: constructorName } = value; const obj = new globalThis[constructorName]( - this._mainBinChunk.buffer, - this._mainBinChunk.byteOffset + offset, + this._mainBinChunk$.buffer, + this._mainBinChunk$.byteOffset + offset, length, ); return obj; } - private _deserializeArray (value: SerializedValue[]): unknown[] { + private _deserializeArray$ (value: SerializedValue[]): unknown[] { const obj = new Array(value.length); let prop: unknown; for (let i = 0; i < value.length; i++) { @@ -525,13 +525,13 @@ class _Deserializer { return obj; } - private _deserializePlainObject (value: Record): Record { + private _deserializePlainObject$ (value: Record): Record { const obj = {}; this._fillPlainObject(obj, value); return obj; } - private _deserializeTypeTaggedObject ( + private _deserializeTypeTaggedObject$ ( value: SerializedGeneralTypedObject, globalIndex: number, owner?: Record | unknown[], @@ -539,11 +539,11 @@ class _Deserializer { ): Record | null { const type = value.__type__ as unknown as string; - const klass = this._classFinder(type, value, owner, propName); + const klass = this._classFinder$(type, value, owner, propName); if (!klass) { - const notReported = this._classFinder === js.getClassById; + const notReported = this._classFinder$ === js.getClassById; if (notReported) { - this._reportMissingClass(type); + this._reportMissingClass$(type); } return null; } @@ -559,32 +559,32 @@ class _Deserializer { if (!(EDITOR && js.isChildClassOf(klass, cclegacy.Component))) { const obj = createObject(klass); - this._deserializeInto(value, obj, klass); + this._deserializeInto$(value, obj, klass); return obj; } else { try { const obj = createObject(klass); - this._deserializeInto(value, obj, klass); + this._deserializeInto$(value, obj, klass); return obj; } catch (e: unknown) { if (DEBUG) { error(`Deserialize ${klass.name} failed, ${(e as { stack: string; }).stack}`); } const obj = createObject(MissingScript); - this._deserializeInto(value, obj, MissingScript); + this._deserializeInto$(value, obj, MissingScript); return obj; } } } - private _deserializeInto ( + private _deserializeInto$ ( value: SerializedGeneralTypedObject, object: Record, constructor: deserialize.SerializableClassConstructor, skipCustomized = false, ): void { if (!skipCustomized && (object as Partial)[deserializeTag]) { - this._runCustomizedDeserialize( + this._runCustomizedDeserialize$( value, object as Record & CustomSerializable, constructor, @@ -600,13 +600,13 @@ class _Deserializer { } if (cclegacy.Class._isCCClass(constructor)) { - this._deserializeFireClass(object, value, constructor as CCClassConstructor); + this._deserializeFireClass$(object, value, constructor as CCClassConstructor); } else { this._deserializeFastDefinedObject(object, value, constructor); } } - private _runCustomizedDeserialize ( + private _runCustomizedDeserialize$ ( value: SerializedGeneralTypedObject, object: Record & CustomSerializable, constructor: deserialize.SerializableClassConstructor, @@ -617,26 +617,26 @@ class _Deserializer { if (typeof serializedField !== 'object' || !serializedField) { return serializedField as unknown; } else { - return this._deserializeObjectField(serializedField) as unknown; + return this._deserializeObjectField$(serializedField) as unknown; } }, readThis: () => { - this._deserializeInto(value, object, constructor, true); + this._deserializeInto$(value, object, constructor, true); }, readSuper: () => { const superConstructor = js.getSuper(constructor); if (superConstructor) { - this._deserializeInto(value, object, superConstructor); + this._deserializeInto$(value, object, superConstructor); } }, }; - object[deserializeTag]!(serializationInput, this._context); + object[deserializeTag]!(serializationInput, this._context$); } - private _deserializeFireClass (obj: Record, serialized: SerializedGeneralTypedObject, klass: CCClassConstructor): void { + private _deserializeFireClass$ (obj: Record, serialized: SerializedGeneralTypedObject, klass: CCClassConstructor): void { let deserialize: CompiledDeserializeFn; // eslint-disable-next-line no-prototype-builtins if (klass.hasOwnProperty('__deserialize__')) { @@ -691,13 +691,13 @@ class _Deserializer { obj[propName] = field; } else { // TODO: assertion - const source = (this._serializedData as SerializedObject[])[id]; + const source = (this._serializedData$ as SerializedObject[])[id]; if (EDITOR || TEST) { - obj[propName] = this._deserializeObject(source, id, obj, propName); + obj[propName] = this._deserializeObject$(source, id, obj, propName); } else { - obj[propName] = this._deserializeObject(source, id, undefined, propName); + obj[propName] = this._deserializeObject$(source, id, undefined, propName); } - this._onDereferenced?.(this.deserializedList, id, obj, propName); + this._onDereferenced$?.(this.deserializedList, id, obj, propName); } } else { const uuid = (serializedField as Partial).__uuid__; @@ -705,15 +705,15 @@ class _Deserializer { const expectedType = (serializedField as SerializedUUIDReference).__expectedType__; this.result.push(obj, propName, uuid, expectedType); } else if (EDITOR || TEST) { - obj[propName] = this._deserializeObject(serializedField as SerializedObject, -1, obj, propName); + obj[propName] = this._deserializeObject$(serializedField as SerializedObject, -1, obj, propName); } else { - obj[propName] = this._deserializeObject(serializedField as SerializedObject, -1); + obj[propName] = this._deserializeObject$(serializedField as SerializedObject, -1); } } return false; } - private _deserializeObjectField (serializedField: SerializedFieldObjectValue): Record | null { + private _deserializeObjectField$ (serializedField: SerializedFieldObjectValue): Record | null { const id = (serializedField as Partial).__id__; if (typeof id === 'number') { const field = this.deserializedList[id]; @@ -721,8 +721,8 @@ class _Deserializer { return field; } else { // TODO: assertion - const source = (this._serializedData as SerializedObject[])[id]; - const field = this._deserializeObject(source, id, undefined, undefined); + const source = (this._serializedData$ as SerializedObject[])[id]; + const field = this._deserializeObject$(source, id, undefined, undefined); return field; } } else { @@ -731,7 +731,7 @@ class _Deserializer { const _expectedType = (serializedField as SerializedUUIDReference).__expectedType__; throw new Error(`Asset reference field serialization is currently not supported in custom serialization.`); } else { - return this._deserializeObject(serializedField as SerializedObject, -1); + return this._deserializeObject$(serializedField as SerializedObject, -1); } } } diff --git a/cocos/sorting/sorting-layers.ts b/cocos/sorting/sorting-layers.ts index 62a580af912..0c001f7c9f7 100644 --- a/cocos/sorting/sorting-layers.ts +++ b/cocos/sorting/sorting-layers.ts @@ -24,7 +24,7 @@ import { EDITOR } from 'internal:constants'; import { director } from '../game/director'; import { Game, game } from '../game'; import { errorID } from '../core/platform/debug'; -import { Settings, settings } from '../core/settings'; +import { settings, SettingsCategory } from '../core/settings'; import { Enum } from '../core/value-types'; interface SortingItem { @@ -48,7 +48,7 @@ game.on(Game.EVENT_POST_SUBSYSTEM_INIT, () => { * In the sorting component, layer has higher sorting priority than sortingOrder. * */ export class SortingLayers { - private static nameMap = new Map(); + private static nameMap$ = new Map(); private static indexMap = new Map(); /** @@ -94,8 +94,8 @@ export class SortingLayers { */ public static getLayerName (layer = 0): string { let name = ''; - if (this.nameMap.has(layer)) { - name = this.nameMap.get(layer)!; + if (this.nameMap$.has(layer)) { + name = this.nameMap$.get(layer)!; } else { errorID(2105); } @@ -107,12 +107,12 @@ export class SortingLayers { * @en Get Layer id by name */ public static getLayerByName (name: string): number { - const count = this.nameMap.size; - const keyIterator = this.nameMap.keys(); + const count = this.nameMap$.size; + const keyIterator = this.nameMap$.keys(); let key = 0; for (let i = 0; i < count; i++) { key = keyIterator.next().value; - if (this.nameMap.get(key) === name) return key; + if (this.nameMap$.get(key) === name) return key; } errorID(2106); return 0; @@ -146,7 +146,7 @@ export class SortingLayers { * @engineInternal */ public static init (): void { - let sortingLayers = settings.querySettings>(Settings.Category.ENGINE, 'sortingLayers'); + let sortingLayers = settings.querySettings>(SettingsCategory.ENGINE, 'sortingLayers'); if (!sortingLayers || sortingLayers.length === 0) { sortingLayers = this.getBuiltinLayers(); } @@ -178,8 +178,8 @@ export class SortingLayers { /** * @engineInternal */ - public static setLayer (layer, layerName, layerIndex): void { - this.nameMap.set(layer, layerName); + public static setLayer (layer: number, layerName: string, layerIndex: number): void { + this.nameMap$.set(layer, layerName); this.indexMap.set(layer, layerIndex); } @@ -193,6 +193,6 @@ export class SortingLayers { delete SortingLayers.Enum[oldItem[i]]; } SortingLayers.indexMap.clear(); - SortingLayers.nameMap.clear(); + SortingLayers.nameMap$.clear(); } } diff --git a/cocos/spine/assembler/simple.ts b/cocos/spine/assembler/simple.ts index 660ae7a5ca6..bab9885f9c4 100644 --- a/cocos/spine/assembler/simple.ts +++ b/cocos/spine/assembler/simple.ts @@ -32,7 +32,7 @@ import { BlendFactor } from '../../gfx'; import { legacyCC } from '../../core/global-exports'; import { RenderData } from '../../2d/renderer/render-data'; import { director } from '../../game'; -import spine from '../lib/spine-core.js'; +import spine from '../lib/spine-core'; import { Color, EPSILON, Vec3 } from '../../core'; import { MaterialInstance } from '../../render-scene'; diff --git a/cocos/spine/lib/spine-define.ts b/cocos/spine/lib/spine-define.ts index 0d8e654e581..d2ae192fb63 100644 --- a/cocos/spine/lib/spine-define.ts +++ b/cocos/spine/lib/spine-define.ts @@ -24,10 +24,10 @@ /* eslint @typescript-eslint/no-explicit-any: "off" */ /* eslint @typescript-eslint/no-unsafe-argument: "off" */ -import spine from './spine-core.js'; +import spine from './spine-core'; import { js } from '../../core'; -function resizeArray (array, newSize): Array { +function resizeArray (array: any[], newSize: number): any[] { if (!array) return new Array(newSize); if (newSize === array.length) return array; if (newSize < array.length) return array.slice(0, newSize); @@ -40,7 +40,7 @@ function overrideDefineArrayProp (prototype: any, getPropVector: any, name: stri get (): any[] { const vectors = getPropVector.call(this); const count = vectors.size(); - let array = this[_name]; + let array = this[_name] as any[]; array = resizeArray(array, count); for (let i = 0; i < count; i++) array[i] = vectors.get(i); this[_name] = array; @@ -75,10 +75,10 @@ function overrideDefineArrayArrayProp (prototype: any, getPropVector: any, name: function overrideDefineArrayFunction (prototype: any, getPropVector: any, name: string): void { const _name = `_${name}`; Object.defineProperty(prototype, name, { - value () { + value (): any[] { const vectors = getPropVector.call(this); const count = vectors.size(); - let array = this[_name]; + let array = this[_name] as any[]; array = resizeArray(array, count); for (let i = 0; i < count; i++) array[i] = vectors.get(i); this[_name] = array; diff --git a/cocos/spine/skeleton-cache.ts b/cocos/spine/skeleton-cache.ts index f9ada2e52f9..e10ba8224ae 100644 --- a/cocos/spine/skeleton-cache.ts +++ b/cocos/spine/skeleton-cache.ts @@ -25,7 +25,7 @@ import { TrackEntryListeners } from './track-entry-listeners'; import { vfmtPosUvColor4B, vfmtPosUvTwoColor4B, getAttributeStride } from '../2d/renderer/vertex-format'; -import spine from './lib/spine-core.js'; +import spine from './lib/spine-core'; import { SkeletonData } from './skeleton-data'; import { warn } from '../core/platform/debug'; @@ -170,7 +170,7 @@ export class AnimationCache { const vUint8Buf = new Uint8Array(Float32Array.BYTES_PER_ELEMENT * floatStride * vc); const iUint16Buf = new Uint16Array(ic); - const HEAPU8 = spine.wasmUtil.wasm.HEAPU8; + const HEAPU8: Uint8Array = spine.wasmUtil.wasm.HEAPU8; const vPtr = model.vPtr; const vLength = vc * Float32Array.BYTES_PER_ELEMENT * floatStride; // eslint-disable-next-line @typescript-eslint/restrict-plus-operands diff --git a/cocos/spine/skeleton-data.ts b/cocos/spine/skeleton-data.ts index 055e9558702..97d391adc6d 100644 --- a/cocos/spine/skeleton-data.ts +++ b/cocos/spine/skeleton-data.ts @@ -26,7 +26,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { CCString, Enum, error } from '../core'; import SkeletonCache from './skeleton-cache'; import { Skeleton } from './skeleton'; -import spine from './lib/spine-core.js'; +import spine from './lib/spine-core'; import { ccclass, serializable, type } from '../core/data/decorators'; import { legacyCC } from '../core/global-exports'; import { Texture2D, Asset } from '../asset/assets'; diff --git a/cocos/spine/skeleton-system.ts b/cocos/spine/skeleton-system.ts index 109f6b7b3cd..d95e6cbd24a 100644 --- a/cocos/spine/skeleton-system.ts +++ b/cocos/spine/skeleton-system.ts @@ -22,12 +22,10 @@ THE SOFTWARE. */ -import { EDITOR_NOT_IN_PREVIEW, JSB } from 'internal:constants'; import { director } from '../game/director'; import { System } from '../core'; import { Skeleton } from './skeleton'; import { legacyCC } from '../core/global-exports'; -import spine from './lib/spine-core.js'; export class SkeletonSystem extends System { /** diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 27daeb4fd32..67eb39aba9a 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -38,7 +38,7 @@ import { legacyCC } from '../core/global-exports'; import { SkeletonSystem } from './skeleton-system'; import { RenderEntity, RenderEntityType } from '../2d/renderer/render-entity'; import { AttachUtil } from './attach-util'; -import spine from './lib/spine-core.js'; +import spine from './lib/spine-core'; import { VertexEffectDelegate } from './vertex-effect-delegate'; import SkeletonCache, { AnimationCache, AnimationFrame, SkeletonCacheItemInfo } from './skeleton-cache'; import { TrackEntryListeners } from './track-entry-listeners'; @@ -62,7 +62,7 @@ export const timeScale = 1.0; * @en Enum for animation cache mode type. * @zh Spine 动画缓存类型。 */ -export enum AnimationCacheMode { +export enum SpineAnimationCacheMode { /** * @en Unset mode. * @zh 未设置模式。 @@ -84,7 +84,7 @@ export enum AnimationCacheMode { */ PRIVATE_CACHE = 2, } -ccenum(AnimationCacheMode); +ccenum(SpineAnimationCacheMode); interface AnimationItem { animationName: string; @@ -103,10 +103,10 @@ ccenum(DefaultSkinsEnum); /** * @engineInternal */ -export enum DefaultAnimsEnum { +export enum SpineDefaultAnimsEnum { '' = 0 } -ccenum(DefaultAnimsEnum); +ccenum(SpineDefaultAnimsEnum); /** * @engineInternal @@ -197,7 +197,7 @@ js.setClassAlias(SpineSocket, 'sp.Skeleton.SpineSocket'); @executeInEditMode export class Skeleton extends UIRenderer { public static SpineSocket = SpineSocket; - public static AnimationCacheMode = AnimationCacheMode; + public static AnimationCacheMode = SpineAnimationCacheMode; @serializable protected _skeletonData: SkeletonData | null = null; @@ -217,9 +217,9 @@ export class Skeleton extends UIRenderer { @serializable protected _timeScale = 1; @serializable - protected _preCacheMode: AnimationCacheMode = AnimationCacheMode.UNSET; + protected _preCacheMode: SpineAnimationCacheMode = SpineAnimationCacheMode.UNSET; @serializable - protected _cacheMode = AnimationCacheMode.REALTIME; + protected _cacheMode = SpineAnimationCacheMode.REALTIME; @serializable protected _sockets: SpineSocket[] = []; @serializable @@ -419,7 +419,7 @@ export class Skeleton extends UIRenderer { * @engineInternal */ @displayName('Animation') - @type(DefaultAnimsEnum) + @type(SpineDefaultAnimsEnum) @tooltip('i18n:COMPONENT.skeleton.animation') get _animationIndex (): number { const animationName = EDITOR_NOT_IN_PREVIEW ? this.defaultAnimation : this.animation; @@ -471,11 +471,11 @@ export class Skeleton extends UIRenderer { @displayName('Animation Cache Mode') @tooltip('i18n:COMPONENT.skeleton.animation_cache_mode') @editable - @type(AnimationCacheMode) - get defaultCacheMode (): AnimationCacheMode { + @type(SpineAnimationCacheMode) + get defaultCacheMode (): SpineAnimationCacheMode { return this._cacheMode; } - set defaultCacheMode (mode: AnimationCacheMode) { + set defaultCacheMode (mode: SpineAnimationCacheMode) { this._cacheMode = mode; this.setAnimationCacheMode(this._cacheMode); } @@ -792,9 +792,9 @@ export class Skeleton extends UIRenderer { public setSkeletonData (skeletonData: spine.SkeletonData): void { if (!EDITOR_NOT_IN_PREVIEW) { const preSkeletonCache = this._skeletonCache; - if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) { + if (this._cacheMode === SpineAnimationCacheMode.SHARED_CACHE) { this._skeletonCache = SkeletonCache.sharedCache; - } else if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) { + } else if (this._cacheMode === SpineAnimationCacheMode.PRIVATE_CACHE) { this._skeletonCache = new SkeletonCache(); this._skeletonCache.enablePrivateMode(); } else { @@ -1249,7 +1249,7 @@ export class Skeleton extends UIRenderer { if (this.skeletonData) { animEnum = this.skeletonData.getAnimsEnum(); } else { - animEnum = DefaultAnimsEnum; + animEnum = SpineDefaultAnimsEnum; } // reset enum type @@ -1322,7 +1322,7 @@ export class Skeleton extends UIRenderer { */ public isAnimationCached (): boolean { if (EDITOR_NOT_IN_PREVIEW) return false; - return this._cacheMode !== AnimationCacheMode.REALTIME; + return this._cacheMode !== SpineAnimationCacheMode.REALTIME; } /** * @en @@ -1335,7 +1335,7 @@ export class Skeleton extends UIRenderer { * @example * skeleton.setAnimationCacheMode(sp.Skeleton.AnimationCacheMode.SHARED_CACHE); */ - public setAnimationCacheMode (cacheMode: AnimationCacheMode): void { + public setAnimationCacheMode (cacheMode: SpineAnimationCacheMode): void { if (this._preCacheMode !== cacheMode) { this._cacheMode = cacheMode; this._preCacheMode = cacheMode; diff --git a/cocos/spine/track-entry-listeners.ts b/cocos/spine/track-entry-listeners.ts index eb501275658..5e98bdff5a8 100644 --- a/cocos/spine/track-entry-listeners.ts +++ b/cocos/spine/track-entry-listeners.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import spine from './lib/spine-core.js'; +import spine from './lib/spine-core'; import { warn } from '../core'; let _listener_ID = 0; @@ -138,7 +138,7 @@ export class TrackEntryListeners { return id; } - static removeListener(id: number): void { + static removeListener (id: number): void { TrackEntryListeners._listenerSet.delete(id); } diff --git a/cocos/spine/vertex-effect-delegate.ts b/cocos/spine/vertex-effect-delegate.ts index 1fd12ac1423..15d3a64d24f 100644 --- a/cocos/spine/vertex-effect-delegate.ts +++ b/cocos/spine/vertex-effect-delegate.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -import spine from './lib/spine-core.js'; +import spine from './lib/spine-core'; /** * @en diff --git a/cocos/tiledmap/assembler/simple.ts b/cocos/tiledmap/assembler/simple.ts index ab5269a6900..3ea2e59bb48 100644 --- a/cocos/tiledmap/assembler/simple.ts +++ b/cocos/tiledmap/assembler/simple.ts @@ -28,7 +28,7 @@ import { IAssembler } from '../../2d/renderer/base'; import { IBatcher } from '../../2d/renderer/i-batcher'; import { TiledLayer, TiledRenderData, TiledTile } from '..'; import { GID, MixedGID, RenderOrder, TiledGrid, TileFlag } from '../tiled-types'; -import { director, Director } from '../../game'; +import { director, DirectorEvent } from '../../game'; import { StaticVBAccessor } from '../../2d/renderer/static-vb-accessor'; import { vfmtPosUvColor } from '../../2d/renderer/vertex-format'; import { RenderData } from '../../2d/renderer/render-data'; @@ -56,8 +56,8 @@ let _moveX = 0; let _moveY = 0; let _fillCount = 0; -let _curTexture : Texture2D | null = null; -let _tempBuffers : Float32Array; +let _curTexture: Texture2D | null = null; +let _tempBuffers: Float32Array; let _curLayer: TiledLayer; let flipTexture: (grid: TiledGrid, gid: MixedGID) => void; @@ -74,7 +74,7 @@ export const simple: IAssembler = { const batcher = director.root!.batcher2D; _accessor = new StaticVBAccessor(device, vfmtPosUvColor, this.vCount); //batcher.registerBufferAccessor(Number.parseInt('TILED-MAP', 36), _accessor); - director.on(Director.EVENT_BEFORE_DRAW, () => { + director.on(DirectorEvent.BEFORE_DRAW, () => { _accessor.reset(); }); } @@ -325,8 +325,13 @@ function packRenderData (): void { // rowMoveDir is -1 or 1, -1 means decrease, 1 means increase // colMoveDir is -1 or 1, -1 means decrease, 1 means increase -function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: number, row: number }, - rowMoveDir: number, colMoveDir: number, comp: TiledLayer): void { +function traverseGrids ( + leftDown: { col: number, row: number }, + rightTop: { col: number, row: number }, + rowMoveDir: number, + colMoveDir: number, + comp: TiledLayer, +): void { // show nothing if (rightTop.row < 0 || rightTop.col < 0) return; @@ -535,8 +540,16 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: packRenderData(); } -function fillByTiledNode (tiledNode: Node, color: Float32Array, vbuf: Float32Array, - left: number, right: number, top: number, bottom: number, diamondTile: boolean): void { +function fillByTiledNode ( + tiledNode: Node, + color: Float32Array, + vbuf: Float32Array, + left: number, + right: number, + top: number, + bottom: number, + diamondTile: boolean, +): void { const vertStep = 9; const vertStep2 = vertStep * 2; const vertStep3 = vertStep * 3; diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index b944adcb78d..a7266900982 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -73,7 +73,18 @@ interface TiledSubNodeData { subNodes: (null | TiledUserNodeData)[]; } - type TiledDataArray = (TiledRenderData | TiledSubNodeData)[]; +type TiledDataArray = (TiledRenderData | TiledSubNodeData)[]; + +export interface ITiledLayerCullingRect { + leftDown: { + row: number; + col: number; + }; + rightTop: { + row: number; + col: number; + }; +} /** * @en Render the TMX layer. @@ -97,27 +108,20 @@ export class TiledLayer extends UIRenderer { // _tilesetIndexToArrIndex: { [key: number]: number } = {}; protected _viewPort = { x: -1, y: -1, width: -1, height: -1 }; - protected _cullingRect = { + protected _cullingRect: ITiledLayerCullingRect = { leftDown: { row: -1, col: -1 }, rightTop: { row: -1, col: -1 }, }; - get cullingRect (): { - leftDown: { - row: number; - col: number; - }; - rightTop: { - row: number; - col: number; - }; - } { return this._cullingRect; } + get cullingRect (): ITiledLayerCullingRect { + return this._cullingRect; + } protected _cullingDirty = true; protected _rightTop = { row: -1, col: -1 }; get rightTop (): { row: number; col: number; - } { return this._rightTop; } + } { return this._rightTop; } protected _layerInfo: TMXLayerInfo | null = null; protected _mapInfo: TMXMapInfo | null = null; @@ -370,7 +374,7 @@ export class TiledLayer extends UIRenderer { const rowData = this._userNodeGrid[row]; const colData = rowData && rowData[col]; if (colData) { - rowData!.count--; + rowData.count--; colData.count--; colData.list[index] = null; if (colData.count <= 0) { @@ -525,7 +529,7 @@ export class TiledLayer extends UIRenderer { * cc.log("Pos: " + pos); */ public getPositionAt (pos: IVec2Like | number, y?: number): Vec2 | null { - let x; + let x: number; if (y !== undefined) { x = Math.floor(pos as number); y = Math.floor(y); diff --git a/cocos/tiledmap/tiled-map.ts b/cocos/tiledmap/tiled-map.ts index 1c874976990..ba7aac2692e 100644 --- a/cocos/tiledmap/tiled-map.ts +++ b/cocos/tiledmap/tiled-map.ts @@ -34,7 +34,7 @@ import { TiledObjectGroup } from './tiled-object-group'; import { TiledMapAsset } from './tiled-map-asset'; import { Sprite } from '../2d/components/sprite'; import { fillTextureGrids } from './tiled-utils'; -import { Size, Vec2, logID, Color, sys } from '../core'; +import { Size, Vec2, logID, Color, sys, warnID } from '../core'; import { SpriteFrame } from '../2d/assets'; import { NodeEventType } from '../scene-graph/node-event'; import { Node } from '../scene-graph'; @@ -455,7 +455,7 @@ export class TiledMap extends Component { const tilesetInfo = tilesets[i]; if (!tilesetInfo) continue; if (!tilesetInfo.sourceImage) { - console.warn(`Can't find the spriteFrame of tilesets ${i}`); + warnID(16406, i); continue; } fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage); diff --git a/cocos/tiledmap/tmx-xml-parser.ts b/cocos/tiledmap/tmx-xml-parser.ts index 0d36df203c6..76fefb5a866 100644 --- a/cocos/tiledmap/tmx-xml-parser.ts +++ b/cocos/tiledmap/tmx-xml-parser.ts @@ -23,8 +23,8 @@ */ import { Label, HorizontalTextAlignment, VerticalTextAlignment } from '../2d/components/label'; -import codec from '../../external/compression/ZipUtils.js'; -import zlib from '../../external/compression/zlib.min.js'; +import codec from '../../external/compression/ZipUtils'; +import zlib from '../../external/compression/zlib.min'; import { SAXParser } from '../asset/asset-manager/plist-parser'; import { GID, MixedGID, Orientation, PropertiesInfo, RenderOrder, StaggerAxis, StaggerIndex, TiledAnimation, TiledAnimationType, diff --git a/cocos/tween/actions/action-manager.ts b/cocos/tween/actions/action-manager.ts index b2257125af9..e2c98d44238 100644 --- a/cocos/tween/actions/action-manager.ts +++ b/cocos/tween/actions/action-manager.ts @@ -26,7 +26,7 @@ */ import { errorID, logID } from '../../core/platform/debug'; -import { Action } from './action'; +import { Action, ActionEnum } from './action'; import { isCCObject } from '../../core/data/object'; import { Node, NodeEventType } from '../../scene-graph'; @@ -267,7 +267,7 @@ export class ActionManager { * @param {T} target */ removeActionByTag (tag: number, target?: T): void { - if (tag === Action.TAG_INVALID) logID(1002); + if (tag === ActionEnum.TAG_INVALID) logID(1002); const hashTargets = this._hashTargets; if (target) { @@ -290,7 +290,7 @@ export class ActionManager { * @param {T} target */ removeAllActionsByTag (tag: number, target?: T): void { - if (tag === Action.TAG_INVALID) logID(1002); + if (tag === ActionEnum.TAG_INVALID) logID(1002); const hashTargets = this._hashTargets; if (target) { @@ -314,7 +314,7 @@ export class ActionManager { * @return {Action|null} return the Action with the given tag on success */ getActionByTag (tag: number, target: T): Action | null { - if (tag === Action.TAG_INVALID) logID(1004); + if (tag === ActionEnum.TAG_INVALID) logID(1004); const element = this._hashTargets.get(target); if (element) { diff --git a/cocos/tween/actions/action.ts b/cocos/tween/actions/action.ts index ba0d067c87a..b7dbcbcbc87 100644 --- a/cocos/tween/actions/action.ts +++ b/cocos/tween/actions/action.ts @@ -25,12 +25,7 @@ THE SOFTWARE. */ -/** - * @en Base classAction for action classes. - * @zh Action 类是所有动作类型的基类。 - * @class Action - */ -export abstract class Action { +export enum ActionEnum { /** * @en Default Action tag. * @zh 默认动作标签。 @@ -38,8 +33,15 @@ export abstract class Action { * @static * @default -1 */ - static TAG_INVALID = -1; + TAG_INVALID = -1, +} +/** + * @en Base classAction for action classes. + * @zh Action 类是所有动作类型的基类。 + * @class Action + */ +export abstract class Action { /** * The `originalTarget` and `target` are both assigned in `startWithTarget` method, * and they get the same value normally. The difference between `originalTarget` and @@ -91,7 +93,7 @@ export abstract class Action { */ public workerTarget: unknown = null; - protected tag = Action.TAG_INVALID; + protected tag = ActionEnum.TAG_INVALID; /** * @en The identifier that to mark an internal action. diff --git a/cocos/tween/tween-system.ts b/cocos/tween/tween-system.ts index 8f02bc5c6a5..528e80b5e26 100644 --- a/cocos/tween/tween-system.ts +++ b/cocos/tween/tween-system.ts @@ -25,7 +25,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { System } from '../core'; import { ActionManager } from './actions/action-manager'; -import { Director, director } from '../game'; +import { director, DirectorEvent } from '../game'; /** * @en @@ -80,7 +80,7 @@ export class TweenSystem extends System { } } -director.on(Director.EVENT_INIT, () => { +director.on(DirectorEvent.INIT, () => { const sys = new TweenSystem(); (TweenSystem as any).instance = sys; director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM); diff --git a/cocos/tween/tween.ts b/cocos/tween/tween.ts index 03958c33b38..a97101cce5f 100644 --- a/cocos/tween/tween.ts +++ b/cocos/tween/tween.ts @@ -30,7 +30,7 @@ import { } from './actions/action-interval'; import { removeSelf, show, hide, callFunc, CallFuncCallback } from './actions/action-instant'; import { ActionUnknownDuration } from './actions/action-unknown-duration'; -import { Action, FiniteTimeAction } from './actions/action'; +import { Action, ActionEnum, FiniteTimeAction } from './actions/action'; import { ITweenOption } from './export-api'; import { IInternalTweenOption, TweenAction } from './tween-action'; import { SetAction } from './set-action'; @@ -99,7 +99,7 @@ export class Tween { private _actions: FiniteTimeAction[] = []; private _finalAction: ActionInterval | null = null; private _target: T | null = null; - private _tag = Action.TAG_INVALID; + private _tag = ActionEnum.TAG_INVALID; private _timeScale = 1; constructor (target?: T | null) { diff --git a/cocos/ui/button.ts b/cocos/ui/button.ts index 56dca33191a..8b3f473a619 100644 --- a/cocos/ui/button.ts +++ b/cocos/ui/button.ts @@ -30,11 +30,11 @@ import { SpriteFrame } from '../2d/assets'; import { Component, EventHandler as ComponentEventHandler } from '../scene-graph'; import { UITransform, UIRenderer } from '../2d/framework'; import { EventMouse, EventTouch } from '../input/types'; -import { Color, Vec3 } from '../core/math'; +import { Color, v3, Vec3 } from '../core/math'; import { ccenum } from '../core/value-types/enum'; import { lerp } from '../core/math/utils'; import { Node } from '../scene-graph/node'; -import { Sprite } from '../2d/components/sprite'; +import { Sprite, SpriteEventType } from '../2d/components/sprite'; import { legacyCC } from '../core/global-exports'; import { TransformBit } from '../scene-graph/node-enum'; import { NodeEventType } from '../scene-graph/node-event'; @@ -90,7 +90,7 @@ enum State { * @en The event types of [[Button]]. All button events are distributed by the owner Node, not the component * @zh [[Button]] 的事件类型,注意:事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 */ -export enum EventType { +export enum ButtonEventType { /** * @event click * @param {Event.EventCustom} event @@ -531,7 +531,7 @@ export class Button extends Component { * @en The event types of [[Button]]. All button events are distributed by the owner Node, not the component * @zh [[Button]] 的事件类型,注意:事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 */ - public static EventType = EventType; + public static EventType = ButtonEventType; /** * @en * If Button is clicked, it will trigger event's handler. @@ -570,17 +570,17 @@ export class Button extends Component { protected _zoomScale = 1.2; @serializable protected _target: Node | null = null; - private _pressed = false; - private _hovered = false; - private _fromColor: Color = new Color(); - private _toColor: Color = new Color(); - private _time = 0; - private _transitionFinished = true; - private _fromScale: Vec3 = new Vec3(); - private _toScale: Vec3 = new Vec3(); - private _originalScale: Vec3 | null = null; - private _sprite: Sprite | null = null; - private _targetScale: Vec3 = new Vec3(); + private _pressed$ = false; + private _hovered$ = false; + private _fromColor$: Color = new Color(); + private _toColor$: Color = new Color(); + private _time$ = 0; + private _transitionFinished$ = true; + private _fromScale$: Vec3 = v3(); + private _toScale$: Vec3 = v3(); + private _originalScale$: Vec3 | null = null; + private _sprite$: Sprite | null = null; + private _targetScale$: Vec3 = v3(); constructor () { super(); @@ -601,9 +601,9 @@ export class Button extends Component { if (!EDITOR_NOT_IN_PREVIEW) { this._registerNodeEvent(); } else { - this.node.on(Sprite.EventType.SPRITE_FRAME_CHANGED, (comp: Sprite) => { + this.node.on(SpriteEventType.SPRITE_FRAME_CHANGED, (comp: Sprite) => { if (this._transition === Transition.SPRITE) { - this._setCurrentStateSpriteFrame(comp.spriteFrame); + this._setCurrentStateSpriteFrame$(comp.spriteFrame); } else { // avoid serialization data loss when in no-sprite mode this._normalSprite = null; @@ -621,7 +621,7 @@ export class Button extends Component { if (!EDITOR_NOT_IN_PREVIEW) { this._unregisterNodeEvent(); } else { - this.node.off(Sprite.EventType.SPRITE_FRAME_CHANGED); + this.node.off(SpriteEventType.SPRITE_FRAME_CHANGED); } } @@ -633,7 +633,7 @@ export class Button extends Component { public update (dt: number): void { const target = this.target; - if (this._transitionFinished || !target) { + if (this._transitionFinished$ || !target) { return; } @@ -641,10 +641,10 @@ export class Button extends Component { return; } - this._time += dt; + this._time$ += dt; let ratio = 1.0; if (this._duration > 0) { - ratio = this._time / this._duration; + ratio = this._time$ / this._duration; } if (ratio >= 1) { @@ -653,19 +653,19 @@ export class Button extends Component { if (this._transition === Transition.COLOR) { const renderComp = target._uiProps.uiComp as UIRenderer; - Color.lerp(_tempColor, this._fromColor, this._toColor, ratio); + Color.lerp(_tempColor, this._fromColor$, this._toColor$, ratio); if (renderComp) { renderComp.color = _tempColor; } } else if (this.transition === Transition.SCALE) { - target.getScale(this._targetScale); - this._targetScale.x = lerp(this._fromScale.x, this._toScale.x, ratio); - this._targetScale.y = lerp(this._fromScale.y, this._toScale.y, ratio); - target.setScale(this._targetScale); + target.getScale(this._targetScale$); + this._targetScale$.x = lerp(this._fromScale$.x, this._toScale$.x, ratio); + this._targetScale$.y = lerp(this._fromScale$.y, this._toScale$.y, ratio); + target.setScale(this._targetScale$); } if (ratio === 1) { - this._transitionFinished = true; + this._transitionFinished$ = true; } } @@ -680,8 +680,8 @@ export class Button extends Component { } protected _resetState (): void { - this._pressed = false; - this._hovered = false; + this._pressed$ = false; + this._hovered$ = false; // Restore button status const target = this.target; if (!target) { @@ -693,10 +693,10 @@ export class Button extends Component { if (renderComp) { renderComp.color = this._normalColor; } - } else if (transition === Transition.SCALE && this._originalScale) { - target.setScale(this._originalScale); + } else if (transition === Transition.SCALE && this._originalScale$) { + target.setScale(this._originalScale$); } - this._transitionFinished = true; + this._transitionFinished$ = true; } protected _registerNodeEvent (): void { @@ -708,18 +708,18 @@ export class Button extends Component { this.node.on(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this); this.node.on(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this); - this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); - this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); - this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick, this); - this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); + this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter$, this); + this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit$, this); + this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick$, this); + this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick$, this); } protected _registerTargetEvent (target): void { if (EDITOR_NOT_IN_PREVIEW) { - target.on(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onTargetSpriteFrameChanged, this); - target.on(NodeEventType.COLOR_CHANGED, this._onTargetColorChanged, this); + target.on(SpriteEventType.SPRITE_FRAME_CHANGED, this._onTargetSpriteFrameChanged$, this); + target.on(NodeEventType.COLOR_CHANGED, this._onTargetColorChanged$, this); } - target.on(NodeEventType.TRANSFORM_CHANGED, this._onTargetTransformChanged, this); + target.on(NodeEventType.TRANSFORM_CHANGED, this._onTargetTransformChanged$, this); } protected _unregisterNodeEvent (): void { @@ -731,15 +731,15 @@ export class Button extends Component { this.node.off(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this); this.node.off(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this); - this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); - this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); - this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick, this); - this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this); + this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter$, this); + this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit$, this); + this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick$, this); + this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick$, this); } protected _unregisterTargetEvent (target): void { if (EDITOR_NOT_IN_PREVIEW) { - target.off(Sprite.EventType.SPRITE_FRAME_CHANGED); + target.off(SpriteEventType.SPRITE_FRAME_CHANGED); target.off(NodeEventType.COLOR_CHANGED); } target.off(NodeEventType.TRANSFORM_CHANGED); @@ -755,22 +755,22 @@ export class Button extends Component { protected _applyTarget (): void { if (this.target) { - this._sprite = this._getTargetSprite(this.target); - if (!this._originalScale) { - this._originalScale = new Vec3(); + this._sprite$ = this._getTargetSprite(this.target); + if (!this._originalScale$) { + this._originalScale$ = new Vec3(); } - Vec3.copy(this._originalScale, this.target.scale); + Vec3.copy(this._originalScale$, this.target.scale); this._registerTargetEvent(this.target); } } - private _onTargetSpriteFrameChanged (comp: Sprite): void { + private _onTargetSpriteFrameChanged$ (comp: Sprite): void { if (this._transition === Transition.SPRITE) { - this._setCurrentStateSpriteFrame(comp.spriteFrame); + this._setCurrentStateSpriteFrame$(comp.spriteFrame); } } - private _setCurrentStateSpriteFrame (spriteFrame: SpriteFrame | null): void { + private _setCurrentStateSpriteFrame$ (spriteFrame: SpriteFrame | null): void { if (!spriteFrame) { return; } @@ -792,13 +792,13 @@ export class Button extends Component { } } - private _onTargetColorChanged (color: Color): void { + private _onTargetColorChanged$ (color: Color): void { if (this._transition === Transition.COLOR) { - this._setCurrentStateColor(color); + this._setCurrentStateColor$(color); } } - private _setCurrentStateColor (color: Color): void { + private _setCurrentStateColor$ (color: Color): void { switch (this._getButtonState()) { case State.NORMAL: this._normalColor = color; @@ -817,11 +817,11 @@ export class Button extends Component { } } - private _onTargetTransformChanged (transformBit: TransformBit): void { + private _onTargetTransformChanged$ (transformBit: TransformBit): void { // update originalScale - if ((transformBit & TransformBit.SCALE) && this._originalScale - && this._transition === Transition.SCALE && this._transitionFinished) { - Vec3.copy(this._originalScale, this.target.scale); + if ((transformBit & TransformBit.SCALE) && this._originalScale$ + && this._transition === Transition.SCALE && this._transitionFinished$) { + Vec3.copy(this._originalScale$, this.target.scale); } } @@ -829,7 +829,7 @@ export class Button extends Component { protected _onTouchBegan (event?: EventTouch): void { if (!this._interactable || !this.enabledInHierarchy) { return; } - this._pressed = true; + this._pressed$ = true; this._updateState(); if (event) { event.propagationStopped = true; @@ -837,7 +837,7 @@ export class Button extends Component { } protected _onTouchMove (event?: EventTouch): void { - if (!this._interactable || !this.enabledInHierarchy || !this._pressed) { return; } + if (!this._interactable || !this.enabledInHierarchy || !this._pressed$) { return; } // mobile phone will not emit _onMouseMoveOut, // so we have to do hit test when touch moving if (!event) { @@ -851,15 +851,15 @@ export class Button extends Component { const hit = this.node._uiProps.uiTransformComp!.hitTest(touch.getLocation(), event.windowId); - if (this._transition === Transition.SCALE && this.target && this._originalScale) { + if (this._transition === Transition.SCALE && this.target && this._originalScale$) { if (hit) { - Vec3.copy(this._fromScale, this._originalScale); - Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale); - this._transitionFinished = false; + Vec3.copy(this._fromScale$, this._originalScale$); + Vec3.multiplyScalar(this._toScale$, this._originalScale$, this._zoomScale); + this._transitionFinished$ = false; } else { - this._time = 0; - this._transitionFinished = true; - this.target.setScale(this._originalScale); + this._time$ = 0; + this._transitionFinished$ = true; + this.target.setScale(this._originalScale$); } } else { let state: State; @@ -881,11 +881,11 @@ export class Button extends Component { return; } - if (this._pressed) { + if (this._pressed$) { ComponentEventHandler.emitEvents(this.clickEvents, event); - this.node.emit(EventType.CLICK, this); + this.node.emit(ButtonEventType.CLICK, this); } - this._pressed = false; + this._pressed$ = false; this._updateState(); if (event) { @@ -896,23 +896,23 @@ export class Button extends Component { protected _onTouchCancel (event?: EventTouch): void { if (!this._interactable || !this.enabledInHierarchy) { return; } - this._pressed = false; + this._pressed$ = false; this._updateState(); } protected _onMouseMoveIn (event?: EventMouse): void { - if (this._pressed || !this.interactable || !this.enabledInHierarchy) { return; } + if (this._pressed$ || !this.interactable || !this.enabledInHierarchy) { return; } if (this._transition === Transition.SPRITE && !this._hoverSprite) { return; } - if (!this._hovered) { - this._hovered = true; + if (!this._hovered$) { + this._hovered$ = true; this._updateState(); } } protected _onMouseMoveOut (event?: EventMouse): void { - if (this._hovered) { - this._hovered = false; + if (this._hovered$) { + this._hovered$ = false; this._updateState(); } } @@ -927,16 +927,16 @@ export class Button extends Component { let state = State.NORMAL; if (!this._interactable) { state = State.DISABLED; - } else if (this._pressed) { + } else if (this._pressed$) { state = State.PRESSED; - } else if (this._hovered) { + } else if (this._hovered$) { state = State.HOVER; } return state; } protected _updateColorTransition (state: State): void { - const color = this._getColorByState(state); + const color = this._getColorByState$(state); const renderComp = this.target?.getComponent(UIRenderer); if (!renderComp) { @@ -945,19 +945,19 @@ export class Button extends Component { if (EDITOR_NOT_IN_PREVIEW || state === State.DISABLED) { renderComp.color = color; - this._transitionFinished = true; + this._transitionFinished$ = true; } else { - this._fromColor = renderComp.color.clone(); - this._toColor = color; - this._time = 0; - this._transitionFinished = false; + this._fromColor$ = renderComp.color.clone(); + this._toColor$ = color; + this._time$ = 0; + this._transitionFinished$ = false; } } protected _updateSpriteTransition (state: State): void { - const sprite = this._getSpriteFrameByState(state); - if (this._sprite && sprite) { - this._sprite.spriteFrame = sprite; + const sprite = this._getSpriteFrameByState$(state); + if (this._sprite$ && sprite) { + this._sprite$.spriteFrame = sprite; } } @@ -975,23 +975,23 @@ export class Button extends Component { protected _zoomUp (): void { // skip before __preload() - if (!this._originalScale) { + if (!this._originalScale$) { return; } - Vec3.copy(this._fromScale, this._originalScale); - Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale); - this._time = 0; - this._transitionFinished = false; + Vec3.copy(this._fromScale$, this._originalScale$); + Vec3.multiplyScalar(this._toScale$, this._originalScale$, this._zoomScale); + this._time$ = 0; + this._transitionFinished$ = false; } protected _zoomBack (): void { - if (!this.target || !this._originalScale) { + if (!this.target || !this._originalScale$) { return; } - Vec3.copy(this._fromScale, this.target.scale); - Vec3.copy(this._toScale, this._originalScale); - this._time = 0; - this._transitionFinished = false; + Vec3.copy(this._fromScale$, this.target.scale); + Vec3.copy(this._toScale$, this._originalScale$); + this._time$ = 0; + this._transitionFinished$ = false; } protected _applyTransition (state: State): void { @@ -1005,7 +1005,7 @@ export class Button extends Component { } } - private _getSpriteFrameByState (state: State): SpriteFrame | null { + private _getSpriteFrameByState$ (state: State): SpriteFrame | null { switch (state) { case State.NORMAL: return this._normalSprite; @@ -1024,7 +1024,7 @@ export class Button extends Component { } } - private _getColorByState (state: State): Color { + private _getColorByState$ (state: State): Color { switch (state) { case State.NORMAL: return this._normalColor; @@ -1043,35 +1043,35 @@ export class Button extends Component { } } - private _xrHoverEnter (): void { + private _xrHoverEnter$ (): void { this._onMouseMoveIn(); this._updateState(); } - private _xrHoverExit (): void { + private _xrHoverExit$ (): void { this._onMouseMoveOut(); - if (this._pressed) { - this._pressed = false; + if (this._pressed$) { + this._pressed$ = false; this._updateState(); } } - private _xrClick (): void { + private _xrClick$ (): void { if (!this._interactable || !this.enabledInHierarchy) { return; } - this._pressed = true; + this._pressed$ = true; this._updateState(); } - private _xrUnClick (): void { + private _xrUnClick$ (): void { if (!this._interactable || !this.enabledInHierarchy) { return; } - if (this._pressed) { + if (this._pressed$) { ComponentEventHandler.emitEvents(this.clickEvents, this); - this.node.emit(EventType.CLICK, this); + this.node.emit(ButtonEventType.CLICK, this); } - this._pressed = false; + this._pressed$ = false; this._updateState(); } } diff --git a/cocos/ui/editbox/edit-box-impl.ts b/cocos/ui/editbox/edit-box-impl.ts index 31c2ecb5002..2493056440c 100644 --- a/cocos/ui/editbox/edit-box-impl.ts +++ b/cocos/ui/editbox/edit-box-impl.ts @@ -26,6 +26,7 @@ */ import { screenAdapter } from 'pal/screen-adapter'; +import { HTML5 } from 'internal:constants'; import { BitmapFont } from '../../2d/assets'; import { director } from '../../game/director'; import { game } from '../../game'; @@ -64,15 +65,15 @@ export class EditBoxImpl extends EditBoxImplBase { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _inputMode: InputMode = -1; + public _inputMode: InputMode = -1 as InputMode; /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _inputFlag: InputFlag = -1; + public _inputFlag: InputFlag = -1 as InputFlag; /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _returnType: KeyboardReturnType = -1; + public _returnType: KeyboardReturnType = -1 as KeyboardReturnType; /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @@ -89,26 +90,27 @@ export class EditBoxImpl extends EditBoxImplBase { * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _edTxt: HTMLInputElement | HTMLTextAreaElement | null = null; - private _isTextArea = false; - - private _textLabelFont = null; - private _textLabelFontSize: number | null = null; - private _textLabelFontColor = null; - private _textLabelAlign = null; - private _placeholderLabelFont = null; - private _placeholderLabelFontSize: number | null = null; - private _placeholderLabelFontColor = null; - private _placeholderLabelAlign = null; - private _placeholderLineHeight = null; - private _placeholderStyleSheet: HTMLStyleElement | null = null; - private _domId = `EditBoxId_${++_domCount}`; - private _forceUpdate: boolean = false; + private _isTextArea$ = false; + + private _textLabelFont$ = null; + private _textLabelFontSize$: number | null = null; + private _textLabelFontColor$ = null; + private _textLabelAlign$ = null; + private _placeholderLabelFont$ = null; + private _placeholderLabelFontSize$: number | null = null; + private _placeholderLabelFontColor$ = null; + private _placeholderLabelAlign$ = null; + private _placeholderLineHeight$ = null; + private _placeholderStyleSheet$: HTMLStyleElement | null = null; + private _domId$ = `EditBoxId_${++_domCount}`; + private _forceUpdate$: boolean = false; constructor () { super(); } public init (delegate: EditBox): void { + if (!HTML5) return; if (!delegate) { return; } @@ -130,6 +132,7 @@ export class EditBoxImpl extends EditBoxImplBase { } public clear (): void { + if (!HTML5) return; View.instance.off('canvas-resize', this._resize, this); screenAdapter.off('window-resize', this._resize, this); this._removeEventListeners(); @@ -146,27 +149,30 @@ export class EditBoxImpl extends EditBoxImplBase { } private _resize (): void { - this._forceUpdate = true; + this._forceUpdate$ = true; } // The beforeDraw function should be used here. // Because many attributes are modified after the update is executed, // this can lead to problems with incorrect coordinates. public beforeDraw (): void { + if (!HTML5) return; const node = this._delegate!.node; - if (!node.hasChangedFlags && !this._forceUpdate) { + if (!node.hasChangedFlags && !this._forceUpdate$) { return; } - this._forceUpdate = false; + this._forceUpdate$ = false; this._updateMatrix(); } public setTabIndex (index: number): void { + if (!HTML5) return; this._edTxt!.tabIndex = index; tabIndexUtil.resort(); } public setSize (width: number, height: number): void { + if (!HTML5) return; const elem = this._edTxt; if (elem) { elem.style.width = `${width}px`; @@ -175,11 +181,13 @@ export class EditBoxImpl extends EditBoxImplBase { } public beginEditing (): void { + if (!HTML5) return; if (_currentEditBoxImpl && _currentEditBoxImpl !== this) { _currentEditBoxImpl.setFocus(false); } this._editing = true; + // eslint-disable-next-line @typescript-eslint/no-this-alias _currentEditBoxImpl = this; this._delegate!._editBoxEditingDidBegan(); this._showDom(); @@ -187,41 +195,47 @@ export class EditBoxImpl extends EditBoxImplBase { } public endEditing (): void { + if (!HTML5) return; this._edTxt!.blur(); } private _createInput (): void { - this._isTextArea = false; + if (!HTML5) return; + this._isTextArea$ = false; this._edTxt = ccdocument.createElement('input'); } private _createTextArea (): void { - this._isTextArea = true; + if (!HTML5) return; + this._isTextArea$ = true; this._edTxt = ccdocument.createElement('textarea'); } private _addDomToGameContainer (): void { + if (!HTML5) return; if (game.container && this._edTxt) { game.container.appendChild(this._edTxt); - ccdocument.head.appendChild(this._placeholderStyleSheet!); + ccdocument.head.appendChild(this._placeholderStyleSheet$!); } } private _removeDomFromGameContainer (): void { + if (!HTML5) return; const hasElem = contains(game.container, this._edTxt); if (hasElem && this._edTxt) { game.container!.removeChild(this._edTxt); } - const hasStyleSheet = contains(ccdocument.head, this._placeholderStyleSheet); + const hasStyleSheet = contains(ccdocument.head, this._placeholderStyleSheet$); if (hasStyleSheet) { - ccdocument.head.removeChild(this._placeholderStyleSheet!); + ccdocument.head.removeChild(this._placeholderStyleSheet$!); } this._edTxt = null; - this._placeholderStyleSheet = null; + this._placeholderStyleSheet$ = null; } private _showDom (): void { + if (!HTML5) return; this._updateMaxLength(); this._updateInputType(); this._updateStyleSheet(); @@ -235,6 +249,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _hideDom (): void { + if (!HTML5) return; const elem = this._edTxt; if (elem && this._delegate) { elem.style.display = 'none'; @@ -246,6 +261,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _showDomOnMobile (): void { + if (!HTML5) return; if (sys.os !== OS.ANDROID && sys.os !== OS.OHOS) { return; } @@ -255,6 +271,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _hideDomOnMobile (): void { + if (!HTML5) return; if (sys.os === OS.ANDROID || sys.os === OS.OHOS) { screenAdapter.handleResizeEvent = true; } @@ -263,6 +280,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _isElementInViewport (): boolean { + if (!HTML5) return false; if (this._edTxt) { const rect = this._edTxt.getBoundingClientRect(); @@ -276,6 +294,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _adjustWindowScroll (): void { + if (!HTML5) return; setTimeout(() => { if (ccwindow.scrollY < SCROLLY && !this._isElementInViewport()) { this._edTxt!.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth' }); @@ -284,6 +303,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _scrollBackWindow (): void { + if (!HTML5) return; setTimeout(() => { if (sys.browserType === BrowserType.WECHAT && sys.os === OS.IOS) { if (ccwindow.top) { @@ -298,6 +318,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _updateMatrix (): void { + if (!HTML5) return; if (!this._edTxt) { return; } @@ -362,6 +383,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _updateInputType (): void { + if (!HTML5) return; const delegate = this._delegate; const inputMode = delegate!.inputMode; const inputFlag = delegate!.inputFlag; @@ -380,7 +402,7 @@ export class EditBoxImpl extends EditBoxImplBase { this._returnType = returnType; // FIX ME: TextArea actually dose not support password type. - if (this._isTextArea) { + if (this._isTextArea$) { // input flag let transform = 'none'; if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { @@ -433,6 +455,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _updateMaxLength (): void { + if (!HTML5) return; let maxLength = this._delegate!.maxLength; if (maxLength < 0) { maxLength = 65535; @@ -441,6 +464,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _initStyleSheet (): void { + if (!HTML5) return; if (!this._edTxt) { return; } @@ -459,9 +483,9 @@ export class EditBoxImpl extends EditBoxImplBase { elem.style.left = `${LEFT_PADDING}px`; elem.className = 'cocosEditBox'; elem.style.fontFamily = 'Arial'; - elem.id = this._domId; + elem.id = this._domId$; - if (!this._isTextArea) { + if (!this._isTextArea$) { elem = elem as HTMLInputElement; elem.type = 'text'; elem.style['-moz-appearance'] = 'textfield'; @@ -470,10 +494,11 @@ export class EditBoxImpl extends EditBoxImplBase { elem.style.overflowY = 'scroll'; } - this._placeholderStyleSheet = ccdocument.createElement('style'); + this._placeholderStyleSheet$ = ccdocument.createElement('style'); } private _updateStyleSheet (): void { + if (!HTML5) return; const delegate = this._delegate; const elem = this._edTxt; if (elem && delegate) { @@ -487,6 +512,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _updateTextLabel (textLabel): void { + if (!HTML5) return; if (!textLabel) { return; } @@ -500,17 +526,17 @@ export class EditBoxImpl extends EditBoxImplBase { const fontSize = textLabel.fontSize * textLabel.node.scale.y; - if (this._textLabelFont === font - && this._textLabelFontSize === fontSize - && this._textLabelFontColor === textLabel.fontColor - && this._textLabelAlign === textLabel.horizontalAlign) { + if (this._textLabelFont$ === font + && this._textLabelFontSize$ === fontSize + && this._textLabelFontColor$ === textLabel.fontColor + && this._textLabelAlign$ === textLabel.horizontalAlign) { return; } - this._textLabelFont = font; - this._textLabelFontSize = fontSize; - this._textLabelFontColor = textLabel.fontColor; - this._textLabelAlign = textLabel.horizontalAlign; + this._textLabelFont$ = font; + this._textLabelFontSize$ = fontSize; + this._textLabelFontColor$ = textLabel.fontColor; + this._textLabelAlign$ = textLabel.horizontalAlign; if (!this._edTxt) { return; @@ -537,6 +563,7 @@ export class EditBoxImpl extends EditBoxImplBase { } private _updatePlaceholderLabel (placeholderLabel): void { + if (!HTML5) return; if (!placeholderLabel) { return; } @@ -550,21 +577,21 @@ export class EditBoxImpl extends EditBoxImplBase { const fontSize = placeholderLabel.fontSize * placeholderLabel.node.scale.y; - if (this._placeholderLabelFont === font - && this._placeholderLabelFontSize === fontSize - && this._placeholderLabelFontColor === placeholderLabel.fontColor - && this._placeholderLabelAlign === placeholderLabel.horizontalAlign - && this._placeholderLineHeight === placeholderLabel.fontSize) { + if (this._placeholderLabelFont$ === font + && this._placeholderLabelFontSize$ === fontSize + && this._placeholderLabelFontColor$ === placeholderLabel.fontColor + && this._placeholderLabelAlign$ === placeholderLabel.horizontalAlign + && this._placeholderLineHeight$ === placeholderLabel.fontSize) { return; } - this._placeholderLabelFont = font; - this._placeholderLabelFontSize = fontSize; - this._placeholderLabelFontColor = placeholderLabel.fontColor; - this._placeholderLabelAlign = placeholderLabel.horizontalAlign; - this._placeholderLineHeight = placeholderLabel.fontSize; + this._placeholderLabelFont$ = font; + this._placeholderLabelFontSize$ = fontSize; + this._placeholderLabelFontColor$ = placeholderLabel.fontColor; + this._placeholderLabelAlign$ = placeholderLabel.horizontalAlign; + this._placeholderLineHeight$ = placeholderLabel.fontSize; - const styleEl = this._placeholderStyleSheet; + const styleEl = this._placeholderStyleSheet$; const fontColor = placeholderLabel.color.toCSS(); const lineHeight = placeholderLabel.fontSize; @@ -583,17 +610,18 @@ 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) { - styleEl!.innerHTML += `#${this._domId}::-ms-clear{display: none;}`; + styleEl!.innerHTML += `#${this._domId$}::-ms-clear{display: none;}`; } } private _registerEventListeners (): void { + if (!HTML5) return; if (!this._edTxt) { return; } @@ -637,7 +665,7 @@ export class EditBoxImpl extends EditBoxImplBase { e.propagationStopped = true; this._delegate!._editBoxEditingReturn(); - if (!this._isTextArea) { + if (!this._isTextArea$) { elem.blur(); } } else if (e.keyCode === KeyCode.TAB) { @@ -667,6 +695,7 @@ export class EditBoxImpl extends EditBoxImplBase { elem.addEventListener('touchstart', cbs.onClick as EventListenerOrEventListenerObject); } private _removeEventListeners (): void { + if (!HTML5) return; if (!this._edTxt) { return; } diff --git a/cocos/ui/editbox/edit-box.ts b/cocos/ui/editbox/edit-box.ts index 293636d4bc7..23f686c4918 100644 --- a/cocos/ui/editbox/edit-box.ts +++ b/cocos/ui/editbox/edit-box.ts @@ -33,14 +33,14 @@ import { Size } from '../../core/math'; import { EventTouch } from '../../input/types'; import { Node } from '../../scene-graph/node'; import { Label, VerticalTextAlignment } from '../../2d/components/label'; -import { Sprite } from '../../2d/components/sprite'; +import { Sprite, SpriteEventType } from '../../2d/components/sprite'; import { EditBoxImpl } from './edit-box-impl'; import { EditBoxImplBase } from './edit-box-impl-base'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; import { legacyCC } from '../../core/global-exports'; import { NodeEventType } from '../../scene-graph/node-event'; import { XrKeyboardEventType, XrUIPressEventType } from '../../xr/event/xr-event-handle'; -import { director, Director } from '../../game/director'; +import { director, DirectorEvent } from '../../game/director'; const LEFT_PADDING = 2; @@ -52,7 +52,7 @@ function capitalizeFirstLetter (str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); } -enum EventType { +enum EditBoxEventType { EDITING_DID_BEGAN = 'editing-did-began', EDITING_DID_ENDED = 'editing-did-ended', TEXT_CHANGED = 'text-changed', @@ -326,7 +326,7 @@ export class EditBox extends Component { * @en Keyboard event enumeration. * @zh 键盘的事件枚举。 */ - public static EventType = EventType; + public static EventType = EditBoxEventType; /** * @en * The event handler to be called when EditBox began to edit text. @@ -444,7 +444,7 @@ export class EditBox extends Component { } public onDestroy (): void { - director.off(Director.EVENT_BEFORE_DRAW, this._beforeDraw, this); + director.off(DirectorEvent.BEFORE_DRAW, this._beforeDraw, this); if (this._impl) { this._impl.clear(); } @@ -497,7 +497,7 @@ export class EditBox extends Component { */ public _editBoxEditingDidBegan (): void { ComponentEventHandler.emitEvents(this.editingDidBegan, this); - this.node.emit(EventType.EDITING_DID_BEGAN, this); + this.node.emit(EditBoxEventType.EDITING_DID_BEGAN, this); } /** @@ -508,7 +508,7 @@ export class EditBox extends Component { */ public _editBoxEditingDidEnded (text?: string): void { ComponentEventHandler.emitEvents(this.editingDidEnded, this); - this.node.emit(EventType.EDITING_DID_ENDED, this, text); + this.node.emit(EditBoxEventType.EDITING_DID_ENDED, this, text); } /** @@ -518,7 +518,7 @@ export class EditBox extends Component { text = this._updateLabelStringStyle(text, true); this.string = text; ComponentEventHandler.emitEvents(this.textChanged, text, this); - this.node.emit(EventType.TEXT_CHANGED, this); + this.node.emit(EditBoxEventType.TEXT_CHANGED, this); } /** @@ -529,7 +529,7 @@ export class EditBox extends Component { */ public _editBoxEditingReturn (text?: string): void { ComponentEventHandler.emitEvents(this.editingReturn, this); - this.node.emit(EventType.EDITING_RETURN, this, text); + this.node.emit(EditBoxEventType.EDITING_RETURN, this, text); } /** @@ -573,7 +573,7 @@ export class EditBox extends Component { this._updateTextLabel(); this._isLabelVisible = true; this.node.on(NodeEventType.SIZE_CHANGED, this._resizeChildNodes, this); - director.on(Director.EVENT_BEFORE_DRAW, this._beforeDraw, this); + director.on(DirectorEvent.BEFORE_DRAW, this._beforeDraw, this); const impl = this._impl = new EditBox._EditBoxImpl(); impl.init(this); @@ -740,12 +740,12 @@ export class EditBox extends Component { private _registerBackgroundEvent (): void { const node = this._background && this._background.node; - node?.on(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this); + node?.on(SpriteEventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this); } private _unregisterBackgroundEvent (): void { const node = this._background && this._background.node; - node?.off(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this); + node?.off(SpriteEventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this); } protected _updateLabelPosition (size: Size): void { @@ -792,7 +792,7 @@ export class EditBox extends Component { } protected _xrUnClick (): void { - this.node.emit(EventType.XR_EDITING_DID_BEGAN, this._maxLength, this.string); + this.node.emit(EditBoxEventType.XR_EDITING_DID_BEGAN, this._maxLength, this.string); } protected _xrKeyBoardInput (str: string): void { diff --git a/cocos/ui/layout.ts b/cocos/ui/layout.ts index f9648dda428..d6970626534 100644 --- a/cocos/ui/layout.ts +++ b/cocos/ui/layout.ts @@ -28,9 +28,9 @@ import { Component } from '../scene-graph/component'; import { Size, Vec2, Vec3 } from '../core/math'; import { ccenum } from '../core/value-types/enum'; import { UITransform } from '../2d/framework/ui-transform'; -import { director, Director } from '../game/director'; +import { director, DirectorEvent } from '../game/director'; import { TransformBit } from '../scene-graph/node-enum'; -import { warn } from '../core'; +import { warnID } from '../core'; import { NodeEventType } from '../scene-graph/node-event'; import { legacyCC } from '../core/global-exports'; import { Node } from '../scene-graph/node'; @@ -40,7 +40,7 @@ import { Node } from '../scene-graph/node'; * * @zh 布局类型。 */ -enum Type { +export enum LayoutType { /** * @en No layout. * @@ -68,14 +68,14 @@ enum Type { GRID = 3, } -ccenum(Type); +ccenum(LayoutType); /** * @en Layout Resize Mode. * * @zh 缩放模式。 */ -enum ResizeMode { +export enum LayoutResizeMode { /** * @en Don't scale. * @@ -96,14 +96,14 @@ enum ResizeMode { CHILDREN = 2, } -ccenum(ResizeMode); +ccenum(LayoutResizeMode); /** * @en Grid Layout start axis direction. * * @zh 布局轴向,只用于 GRID 布局。 */ -enum AxisDirection { +export enum LayoutAxisDirection { /** * @en The horizontal axis. * @@ -118,14 +118,14 @@ enum AxisDirection { VERTICAL = 1, } -ccenum(AxisDirection); +ccenum(LayoutAxisDirection); /** * @en Vertical layout direction. * * @zh 垂直方向布局方式。 */ -enum VerticalDirection { +export enum LayoutVerticalDirection { /** * @en Items arranged from bottom to top. * @@ -139,14 +139,14 @@ enum VerticalDirection { TOP_TO_BOTTOM = 1, } -ccenum(VerticalDirection); +ccenum(LayoutVerticalDirection); /** * @en Horizontal layout direction. * * @zh 水平方向布局方式。 */ -enum HorizontalDirection { +export enum LayoutHorizontalDirection { /** * @en Items arranged from left to right. * @@ -160,14 +160,14 @@ enum HorizontalDirection { RIGHT_TO_LEFT = 1, } -ccenum(HorizontalDirection); +ccenum(LayoutHorizontalDirection); /** * @en Layout constraint. * * @zh 布局约束。 */ -enum Constraint { +export enum LayoutConstraint { /** * @en Constraint free. * @@ -188,7 +188,7 @@ enum Constraint { FIXED_COL = 2, } -ccenum(Constraint); +ccenum(LayoutConstraint); const _tempVec3 = new Vec3(); @@ -224,7 +224,7 @@ export class Layout extends Component { * 横向对齐。在 Type 为 Horizontal 时按同个方向固定起始位置排列。 */ @visible(function (this: Layout): boolean { - return this._layoutType === Type.HORIZONTAL; + return this._layoutType === LayoutType.HORIZONTAL; }) @tooltip('i18n:layout.align_horizontal') get alignHorizontal (): boolean { @@ -232,7 +232,7 @@ export class Layout extends Component { } set alignHorizontal (value) { - if (this._layoutType !== Type.HORIZONTAL) { + if (this._layoutType !== LayoutType.HORIZONTAL) { return; } @@ -248,7 +248,7 @@ export class Layout extends Component { * 纵向对齐。在 Type 为 Horizontal 或 Vertical 时按同个方向固定起始位置排列。 */ @visible(function (this: Layout): boolean { - return this._layoutType === Type.VERTICAL; + return this._layoutType === LayoutType.VERTICAL; }) @tooltip('i18n:layout.align_vertical') get alignVertical (): boolean { @@ -256,7 +256,7 @@ export class Layout extends Component { } set alignVertical (value) { - if (this._layoutType !== Type.VERTICAL) { + if (this._layoutType !== LayoutType.VERTICAL) { return; } @@ -271,14 +271,14 @@ export class Layout extends Component { * @zh * 布局类型。 */ - @type(Type) + @type(LayoutType) @displayOrder(0) @tooltip('i18n:layout.layout_type') - get type (): Type { + get type (): LayoutType { return this._layoutType; } - set type (value: Type) { + set type (value: LayoutType) { this._layoutType = value; this._doLayoutDirty(); } @@ -289,16 +289,16 @@ export class Layout extends Component { * @zh * 缩放模式。 */ - @type(ResizeMode) + @type(LayoutResizeMode) @visible(function (this: Layout): boolean { - return this._layoutType !== Type.NONE; + return this._layoutType !== LayoutType.NONE; }) @tooltip('i18n:layout.resize_mode') - get resizeMode (): ResizeMode { + get resizeMode (): LayoutResizeMode { return this._resizeMode; } set resizeMode (value) { - if (this._layoutType === Type.NONE) { + if (this._layoutType === LayoutType.NONE) { return; } @@ -314,7 +314,7 @@ export class Layout extends Component { * 每个格子的大小,只有布局类型为 GRID 的时候才有效。 */ @visible(function (this: Layout) { - if (this.type === Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { + if (this.type === LayoutType.GRID && this._resizeMode === LayoutResizeMode.CHILDREN) { return true; } @@ -342,9 +342,9 @@ export class Layout extends Component { * @zh * 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 */ - @type(AxisDirection) + @type(LayoutAxisDirection) @tooltip('i18n:layout.start_axis') - get startAxis (): AxisDirection { + get startAxis (): LayoutAxisDirection { return this._startAxis; } @@ -486,13 +486,13 @@ export class Layout extends Component { * @zh * 垂直排列子节点的方向。 */ - @type(VerticalDirection) + @type(LayoutVerticalDirection) @tooltip('i18n:layout.vertical_direction') - get verticalDirection (): VerticalDirection { + get verticalDirection (): LayoutVerticalDirection { return this._verticalDirection; } - set verticalDirection (value: VerticalDirection) { + set verticalDirection (value: LayoutVerticalDirection) { if (this._verticalDirection === value) { return; } @@ -509,13 +509,13 @@ export class Layout extends Component { * @zh * 水平排列子节点的方向。 */ - @type(HorizontalDirection) + @type(LayoutHorizontalDirection) @tooltip('i18n:layout.horizontal_direction') - get horizontalDirection (): HorizontalDirection { + get horizontalDirection (): LayoutHorizontalDirection { return this._horizontalDirection; } - set horizontalDirection (value: HorizontalDirection) { + set horizontalDirection (value: LayoutHorizontalDirection) { if (this._horizontalDirection === value) { return; } @@ -549,17 +549,17 @@ export class Layout extends Component { * @zh * 容器内布局约束。 */ - @type(Constraint) + @type(LayoutConstraint) @visible(function (this: Layout): boolean { - return this.type === Type.GRID; + return this.type === LayoutType.GRID; }) @tooltip('i18n:layout.constraint') - get constraint (): Constraint { + get constraint (): LayoutConstraint { return this._constraint; } - set constraint (value: Constraint) { - if (this._layoutType === Type.NONE || this._constraint === value) { + set constraint (value: LayoutConstraint) { + if (this._layoutType === LayoutType.NONE || this._constraint === value) { return; } @@ -575,7 +575,7 @@ export class Layout extends Component { * 容器内布局约束使用的限定值。 */ @visible(function (this: Layout): boolean { - return this._constraint !== Constraint.NONE; + return this._constraint !== LayoutConstraint.NONE; }) @tooltip('i18n:layout.constraint_number') get constraintNum (): number { @@ -583,12 +583,12 @@ export class Layout extends Component { } set constraintNum (value) { - if (this._constraint === Constraint.NONE || this._constraintNum === value) { + if (this._constraint === LayoutConstraint.NONE || this._constraintNum === value) { return; } if (value <= 0) { - warn('Limit values to be greater than 0'); + warnID(16400); } this._constraintNum = value; @@ -616,41 +616,41 @@ export class Layout extends Component { * @en Layout type. * @zh 布局类型。 */ - public static Type = Type; + public static Type = LayoutType; /** * @en Vertical layout direction. * @zh 垂直方向布局方式。 */ - public static VerticalDirection = VerticalDirection; + public static VerticalDirection = LayoutVerticalDirection; /** * @en Horizontal layout direction. * @zh 水平方向布局方式。 */ - public static HorizontalDirection = HorizontalDirection; + public static HorizontalDirection = LayoutHorizontalDirection; /** * @en Layout Resize Mode. * @zh 缩放模式。 */ - public static ResizeMode = ResizeMode; + public static ResizeMode = LayoutResizeMode; /** * @en Grid Layout start axis direction. * @zh 布局轴向,只用于 GRID 布局。 */ - public static AxisDirection = AxisDirection; + public static AxisDirection = LayoutAxisDirection; /** * @en Layout constraint. * @zh 布局约束。 */ - public static Constraint = Constraint; + public static Constraint = LayoutConstraint; @serializable - protected _resizeMode = ResizeMode.NONE; + protected _resizeMode = LayoutResizeMode.NONE; @serializable - protected _layoutType = Type.NONE; + protected _layoutType = LayoutType.NONE; @serializable protected _cellSize = new Size(40, 40); @serializable - protected _startAxis = AxisDirection.HORIZONTAL; + protected _startAxis = LayoutAxisDirection.HORIZONTAL; @serializable protected _paddingLeft = 0; @serializable @@ -664,11 +664,11 @@ export class Layout extends Component { @serializable protected _spacingY = 0; @serializable - protected _verticalDirection = VerticalDirection.TOP_TO_BOTTOM; + protected _verticalDirection = LayoutVerticalDirection.TOP_TO_BOTTOM; @serializable - protected _horizontalDirection = HorizontalDirection.LEFT_TO_RIGHT; + protected _horizontalDirection = LayoutHorizontalDirection.LEFT_TO_RIGHT; @serializable - protected _constraint = Constraint.NONE; + protected _constraint = LayoutConstraint.NONE; @serializable protected _constraintNum = 2; @serializable @@ -735,7 +735,7 @@ export class Layout extends Component { } protected _addEventListeners (): void { - director.on(Director.EVENT_AFTER_UPDATE, this.updateLayout, this); + director.on(DirectorEvent.AFTER_UPDATE, this.updateLayout, this); this.node.on(NodeEventType.SIZE_CHANGED, this._resized, this); this.node.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.on(NodeEventType.CHILD_ADDED, this._childAdded, this); @@ -746,7 +746,7 @@ export class Layout extends Component { } protected _removeEventListeners (): void { - director.off(Director.EVENT_AFTER_UPDATE, this.updateLayout, this); + director.off(DirectorEvent.AFTER_UPDATE, this.updateLayout, this); this.node.off(NodeEventType.SIZE_CHANGED, this._resized, this); this.node.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this); this.node.off(NodeEventType.CHILD_ADDED, this._childAdded, this); @@ -806,7 +806,7 @@ export class Layout extends Component { let sign = 1; let paddingX = this._paddingLeft; - if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + if (this._horizontalDirection === LayoutHorizontalDirection.RIGHT_TO_LEFT) { sign = -1; paddingX = this._paddingRight; } @@ -821,7 +821,7 @@ export class Layout extends Component { const activeChildCount = this._usefulLayoutObj.length; let newChildWidth = this._cellSize.width; const paddingH = this._getPaddingH(); - if (this._layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { + if (this._layoutType !== LayoutType.GRID && this._resizeMode === LayoutResizeMode.CHILDREN) { newChildWidth = (baseWidth - paddingH - (activeChildCount - 1) * this._spacingX) / activeChildCount; } @@ -833,9 +833,9 @@ export class Layout extends Component { const childScaleX = this._getUsedScaleValue(scale.x); const childScaleY = this._getUsedScaleValue(scale.y); // for resizing children - if (this._resizeMode === ResizeMode.CHILDREN) { + if (this._resizeMode === LayoutResizeMode.CHILDREN) { childTrans.width = newChildWidth / childScaleX; - if (this._layoutType === Type.GRID) { + if (this._layoutType === LayoutType.GRID) { childTrans.height = this._cellSize.height / childScaleY; } } @@ -900,7 +900,7 @@ export class Layout extends Component { let sign = 1; let paddingY = this._paddingBottom; - if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + if (this._verticalDirection === LayoutVerticalDirection.TOP_TO_BOTTOM) { sign = -1; paddingY = this._paddingTop; } @@ -915,7 +915,7 @@ export class Layout extends Component { const activeChildCount = this._usefulLayoutObj.length; let newChildHeight = this._cellSize.height; const paddingV = this._getPaddingV(); - if (this._layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) { + if (this._layoutType !== LayoutType.GRID && this._resizeMode === LayoutResizeMode.CHILDREN) { newChildHeight = (baseHeight - paddingV - (activeChildCount - 1) * this._spacingY) / activeChildCount; } @@ -928,9 +928,9 @@ export class Layout extends Component { const childScaleY = this._getUsedScaleValue(scale.y); // for resizing children - if (this._resizeMode === ResizeMode.CHILDREN) { + if (this._resizeMode === LayoutResizeMode.CHILDREN) { childTrans.height = newChildHeight / childScaleY; - if (this._layoutType === Type.GRID) { + if (this._layoutType === LayoutType.GRID) { childTrans.width = this._cellSize.width / childScaleX; } } @@ -995,7 +995,7 @@ export class Layout extends Component { let sign = 1; let bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height; let paddingY = this._paddingBottom; - if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + if (this._verticalDirection === LayoutVerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height; paddingY = this._paddingTop; @@ -1004,12 +1004,12 @@ export class Layout extends Component { const fnPositionY = (child: Node, childTrans: UITransform, topOffset: number): number => bottomBoundaryOfLayout + sign * (topOffset + (1 - childTrans.anchorY) * childTrans.height * this._getUsedScaleValue(child.scale.y) + paddingY); let newHeight = 0; - if (this._resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === LayoutResizeMode.CONTAINER) { // calculate the new height of container, it won't change the position of it's children newHeight = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false); bottomBoundaryOfLayout = -layoutAnchor.y * newHeight; - if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { + if (this._verticalDirection === LayoutVerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight; } @@ -1017,7 +1017,7 @@ export class Layout extends Component { this._doLayoutHorizontally(baseWidth, true, fnPositionY, true); - if (this._resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === LayoutResizeMode.CONTAINER) { this.node._uiProps.uiTransformComp!.setContentSize(baseWidth, newHeight); } } @@ -1028,7 +1028,7 @@ export class Layout extends Component { let sign = 1; let leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width; let paddingX = this._paddingLeft; - if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + if (this._horizontalDirection === LayoutHorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width; paddingX = this._paddingRight; @@ -1037,12 +1037,12 @@ export class Layout extends Component { const fnPositionX = (child: Node, childTrans: UITransform, leftOffset: number): number => leftBoundaryOfLayout + sign * (leftOffset + (1 - childTrans.anchorX) * childTrans.width * this._getUsedScaleValue(child.scale.x) + paddingX); let newWidth = 0; - if (this._resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === LayoutResizeMode.CONTAINER) { newWidth = this._doLayoutVertically(baseHeight, true, fnPositionX, false); leftBoundaryOfLayout = -layoutAnchor.x * newWidth; - if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { + if (this._horizontalDirection === LayoutHorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth; } @@ -1050,7 +1050,7 @@ export class Layout extends Component { this._doLayoutVertically(baseHeight, true, fnPositionX, true); - if (this._resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === LayoutResizeMode.CONTAINER) { this.node._uiProps.uiTransformComp!.setContentSize(newWidth, baseHeight); } } @@ -1060,9 +1060,9 @@ export class Layout extends Component { const layoutAnchor = trans.anchorPoint; const layoutSize = trans.contentSize; - if (this.startAxis === AxisDirection.HORIZONTAL) { + if (this.startAxis === LayoutAxisDirection.HORIZONTAL) { this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize); - } else if (this.startAxis === AxisDirection.VERTICAL) { + } else if (this.startAxis === LayoutAxisDirection.VERTICAL) { this._doLayoutGridAxisVertical(layoutAnchor, layoutSize); } } @@ -1071,7 +1071,7 @@ export class Layout extends Component { const children = this._usefulLayoutObj; let baseSize = 0; const activeChildCount = children.length; - if (this._resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === LayoutResizeMode.CONTAINER) { for (let i = 0; i < children.length; ++i) { const childTrans = children[i]; const child = childTrans.node; @@ -1091,7 +1091,7 @@ export class Layout extends Component { const children = this._usefulLayoutObj; let baseSize = 0; const activeChildCount = children.length; - if (this._resizeMode === ResizeMode.CONTAINER) { + if (this._resizeMode === LayoutResizeMode.CONTAINER) { for (let i = 0; i < children.length; ++i) { const childTrans = children[i]; const child = childTrans.node; @@ -1114,7 +1114,7 @@ export class Layout extends Component { this._childrenDirty = false; } - if (this._layoutType === Type.HORIZONTAL) { + if (this._layoutType === LayoutType.HORIZONTAL) { const newWidth = this._getHorizontalBaseWidth(); const fnPositionY = (child: Node): number => { @@ -1124,7 +1124,7 @@ export class Layout extends Component { this._doLayoutHorizontally(newWidth, false, fnPositionY, true); this.node._uiProps.uiTransformComp!.width = newWidth; - } else if (this._layoutType === Type.VERTICAL) { + } else if (this._layoutType === LayoutType.VERTICAL) { const newHeight = this._getVerticalBaseHeight(); const fnPositionX = (child: Node): number => { @@ -1134,7 +1134,7 @@ export class Layout extends Component { this._doLayoutVertically(newHeight, false, fnPositionX, true); this.node._uiProps.uiTransformComp!.height = newHeight; - } else if (this._layoutType === Type.GRID) { + } else if (this._layoutType === LayoutType.GRID) { this._doLayoutGrid(); } } @@ -1169,14 +1169,14 @@ export class Layout extends Component { } protected _getFixedBreakingNum (): number { - if (this._layoutType !== Type.GRID || this._constraint === Constraint.NONE || this._constraintNum <= 0) { + if (this._layoutType !== LayoutType.GRID || this._constraint === LayoutConstraint.NONE || this._constraintNum <= 0) { return 0; } - let num = this._constraint === Constraint.FIXED_ROW ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum; + let num = this._constraint === LayoutConstraint.FIXED_ROW ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum; // Horizontal sorting always counts the number of columns - if (this._startAxis === AxisDirection.VERTICAL) { - num = this._constraint === Constraint.FIXED_COL ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum; + if (this._startAxis === LayoutAxisDirection.VERTICAL) { + num = this._constraint === LayoutConstraint.FIXED_COL ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum; } return num; diff --git a/cocos/ui/page-view-indicator.ts b/cocos/ui/page-view-indicator.ts index 88e4777ae42..61192ebabed 100644 --- a/cocos/ui/page-view-indicator.ts +++ b/cocos/ui/page-view-indicator.ts @@ -29,7 +29,7 @@ import { Component } from '../scene-graph/component'; import { Color, Size } from '../core/math'; import { ccenum } from '../core/value-types/enum'; import { Node } from '../scene-graph'; -import { Layout } from './layout'; +import { Layout, LayoutResizeMode, LayoutType } from './layout'; import { PageView } from './page-view'; import { Sprite } from '../2d/components/sprite'; import { UIRenderer } from '../2d/framework/ui-renderer'; @@ -195,13 +195,13 @@ export class PageViewIndicator extends Component { const layout = this._layout!; if (this.direction === Direction.HORIZONTAL) { - layout.type = Layout.Type.HORIZONTAL; + layout.type = LayoutType.HORIZONTAL; layout.spacingX = this.spacing; } else if (this.direction === Direction.VERTICAL) { - layout.type = Layout.Type.VERTICAL; + layout.type = LayoutType.VERTICAL; layout.spacingY = this.spacing; } - layout.resizeMode = Layout.ResizeMode.CONTAINER; + layout.resizeMode = LayoutResizeMode.CONTAINER; } /** diff --git a/cocos/ui/page-view.ts b/cocos/ui/page-view.ts index f34f8f94621..8fc20d24b57 100644 --- a/cocos/ui/page-view.ts +++ b/cocos/ui/page-view.ts @@ -31,7 +31,7 @@ import { v2, v3, Vec2, Vec3 } from '../core/math'; import { ccenum } from '../core/value-types/enum'; import { Layout } from './layout'; import { PageViewIndicator } from './page-view-indicator'; -import { ScrollView, EventType as ScrollEventType } from './scroll-view'; +import { ScrollView, ScrollViewEventType as ScrollEventType } from './scroll-view'; import { ScrollBar } from './scroll-bar'; import { warnID, logID } from '../core/platform/debug'; import { extendsEnum } from '../core/data/utils/extends-enum'; @@ -65,27 +65,27 @@ ccenum(SizeMode); * * @zh 页面视图滚动类型。 */ -enum Direction { +enum PageViewDirection { /** * @en Horizontal scroll. * @zh 水平滚动。 */ - Horizontal = 0, + HORIZONTAL = 0, /** * @en Vertical scroll. * @zh 垂直滚动。 */ - Vertical = 1, + VERTICAL = 1, } -ccenum(Direction); +ccenum(PageViewDirection); /** * @en Enum for ScrollView event type. * * @zh 滚动视图事件类型。 */ -enum EventType { +enum PageViewEventType { PAGE_TURNING = 'page-turning', } @@ -130,9 +130,9 @@ export class PageView extends ScrollView { * @zh * 页面视图滚动类型。 */ - @type(Direction) + @type(PageViewDirection) @tooltip('i18n:pageview.direction') - get direction (): Direction { + get direction (): PageViewDirection { return this._direction; } @@ -227,12 +227,12 @@ export class PageView extends ScrollView { * @en Enum for Page View Direction. * @zh 页面视图滚动类型。 */ - public static Direction = Direction; + public static Direction = PageViewDirection; /** * @en Enum for Page View event. * @zh 页面视图事件枚举 */ - public static EventType = extendsEnum(EventType, ScrollEventType); + public static EventType = extendsEnum(PageViewEventType, ScrollEventType); /** * @en @@ -351,7 +351,7 @@ export class PageView extends ScrollView { @serializable protected _sizeMode = SizeMode.Unified; @serializable - protected _direction = Direction.Horizontal; + protected _direction = PageViewDirection.HORIZONTAL; @serializable protected _scrollThreshold = 0.5; @serializable @@ -587,7 +587,7 @@ export class PageView extends ScrollView { const page = this._pages[i]; // page.setSiblingIndex(i); const pos = page.position; - if (this.direction === Direction.Horizontal) { + if (this.direction === PageViewDirection.HORIZONTAL) { this._scrollCenterOffsetX[i] = Math.abs(contentPos.x + pos.x); } else { this._scrollCenterOffsetY[i] = Math.abs(contentPos.y + pos.y); @@ -652,8 +652,8 @@ export class PageView extends ScrollView { protected _onMouseWheel (): void { } protected _syncScrollDirection (): void { - this.horizontal = this.direction === Direction.Horizontal; - this.vertical = this.direction === Direction.Vertical; + this.horizontal = this.direction === PageViewDirection.HORIZONTAL; + this.vertical = this.direction === PageViewDirection.VERTICAL; } protected _syncSizeMode (): void { @@ -664,10 +664,10 @@ export class PageView extends ScrollView { if (this._sizeMode === SizeMode.Free && this._pages.length > 0) { const firstPageTrans = this._pages[0]._uiProps.uiTransformComp!; const lastPageTrans = this._pages[this._pages.length - 1]._uiProps.uiTransformComp!; - if (this.direction === Direction.Horizontal) { + if (this.direction === PageViewDirection.HORIZONTAL) { layout.paddingLeft = (viewTrans.width - firstPageTrans.width) / 2; layout.paddingRight = (viewTrans.width - lastPageTrans.width) / 2; - } else if (this.direction === Direction.Vertical) { + } else if (this.direction === PageViewDirection.VERTICAL) { layout.paddingTop = (viewTrans.height - firstPageTrans.height) / 2; layout.paddingBottom = (viewTrans.height - lastPageTrans.height) / 2; } @@ -694,17 +694,17 @@ export class PageView extends ScrollView { protected _dispatchPageTurningEvent (): void { if (this._lastPageIdx === this._curPageIdx) { return; } this._lastPageIdx = this._curPageIdx; - ComponentEventHandler.emitEvents(this.pageEvents, this, EventType.PAGE_TURNING); - this.node.emit(EventType.PAGE_TURNING, this); + ComponentEventHandler.emitEvents(this.pageEvents, this, PageViewEventType.PAGE_TURNING); + this.node.emit(PageViewEventType.PAGE_TURNING, this); } // 快速滑动 protected _isQuicklyScrollable (touchMoveVelocity: Vec3): boolean { - if (this.direction === Direction.Horizontal) { + if (this.direction === PageViewDirection.HORIZONTAL) { if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) { return true; } - } else if (this.direction === Direction.Vertical) { + } else if (this.direction === PageViewDirection.VERTICAL) { if (Math.abs(touchMoveVelocity.y) > this.autoPageTurningThreshold) { return true; } @@ -716,9 +716,9 @@ export class PageView extends ScrollView { protected _moveOffsetValue (idx: number): Vec2 { const offset = new Vec2(); if (this._sizeMode === SizeMode.Free) { - if (this.direction === Direction.Horizontal) { + if (this.direction === PageViewDirection.HORIZONTAL) { offset.x = this._scrollCenterOffsetX[idx]; - } else if (this.direction === Direction.Vertical) { + } else if (this.direction === PageViewDirection.VERTICAL) { offset.y = this._scrollCenterOffsetY[idx]; } } else { @@ -726,9 +726,9 @@ export class PageView extends ScrollView { if (!viewTrans) { return offset; } - if (this.direction === Direction.Horizontal) { + if (this.direction === PageViewDirection.HORIZONTAL) { offset.x = idx * viewTrans.width; - } else if (this.direction === Direction.Vertical) { + } else if (this.direction === PageViewDirection.VERTICAL) { offset.y = idx * viewTrans.height; } } @@ -736,7 +736,7 @@ export class PageView extends ScrollView { } protected _getDragDirection (moveOffset: Vec2): number { - if (this._direction === Direction.Horizontal) { + if (this._direction === PageViewDirection.HORIZONTAL) { if (moveOffset.x === 0) { return 0; } @@ -757,11 +757,11 @@ export class PageView extends ScrollView { if (this._sizeMode === SizeMode.Free) { let curPageCenter = 0; let nextPageCenter = 0; - if (this.direction === Direction.Horizontal) { + if (this.direction === PageViewDirection.HORIZONTAL) { curPageCenter = this._scrollCenterOffsetX[index]; nextPageCenter = this._scrollCenterOffsetX[nextIndex]; return Math.abs(offset.x) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold; - } else if (this.direction === Direction.Vertical) { + } else if (this.direction === PageViewDirection.VERTICAL) { curPageCenter = this._scrollCenterOffsetY[index]; nextPageCenter = this._scrollCenterOffsetY[nextIndex]; return Math.abs(offset.y) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold; @@ -771,9 +771,9 @@ export class PageView extends ScrollView { if (!viewTrans) { return false; } - if (this.direction === Direction.Horizontal) { + if (this.direction === PageViewDirection.HORIZONTAL) { return Math.abs(offset.x) >= viewTrans.width * this.scrollThreshold; - } else if (this.direction === Direction.Vertical) { + } else if (this.direction === PageViewDirection.VERTICAL) { return Math.abs(offset.y) >= viewTrans.height * this.scrollThreshold; } } diff --git a/cocos/ui/scroll-bar.ts b/cocos/ui/scroll-bar.ts index 42c41654788..acf6c0fed0c 100644 --- a/cocos/ui/scroll-bar.ts +++ b/cocos/ui/scroll-bar.ts @@ -49,7 +49,7 @@ const _tempVec2 = new Vec2(); * @zh * 滚动条方向。 */ -enum Direction { +enum ScrollBarDirection { /** * @en * Horizontal scroll. @@ -69,7 +69,7 @@ enum Direction { VERTICAL = 1, } -ccenum(Direction); +ccenum(ScrollBarDirection); /** * @en @@ -117,10 +117,10 @@ export class ScrollBar extends Component { * @zh * ScrollBar 的滚动方向。 */ - @type(Direction) + @type(ScrollBarDirection) @displayOrder(1) @tooltip('i18n:scrollbar.direction') - get direction (): Direction { + get direction (): ScrollBarDirection { return this._direction; } @@ -180,13 +180,13 @@ export class ScrollBar extends Component { this._autoHideTime = value; } - public static Direction = Direction; + public static Direction = ScrollBarDirection; @serializable protected _scrollView: ScrollView | null = null; @serializable protected _handle: Sprite | null = null; @serializable - protected _direction = Direction.HORIZONTAL; + protected _direction = ScrollBarDirection.HORIZONTAL; @serializable protected _enableAutoHide = false; @serializable @@ -262,7 +262,7 @@ export class ScrollBar extends Component { const outOfContentPosition = _tempVec2; outOfContentPosition.set(0, 0); - if (this._direction === Direction.HORIZONTAL) { + if (this._direction === ScrollBarDirection.HORIZONTAL) { contentMeasure = contentSize.width; scrollViewMeasure = scrollViewSize.width; handleNodeMeasure = barSize.width; @@ -270,7 +270,7 @@ export class ScrollBar extends Component { this._convertToScrollViewSpace(outOfContentPosition, content); contentPosition = -outOfContentPosition.x; - } else if (this._direction === Direction.VERTICAL) { + } else if (this._direction === ScrollBarDirection.VERTICAL) { contentMeasure = contentSize.height; scrollViewMeasure = scrollViewSize.height; handleNodeMeasure = barSize.height; @@ -407,9 +407,9 @@ export class ScrollBar extends Component { fixupPosition.set(0, 0, 0); handleParent._uiProps.uiTransformComp!.convertToNodeSpaceAR(leftBottomWorldPosition, fixupPosition); - if (this.direction === Direction.HORIZONTAL) { + if (this.direction === ScrollBarDirection.HORIZONTAL) { fixupPosition.set(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2, fixupPosition.z); - } else if (this.direction === Direction.VERTICAL) { + } else if (this.direction === ScrollBarDirection.VERTICAL) { fixupPosition.set(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y, fixupPosition.z); } @@ -417,11 +417,11 @@ export class ScrollBar extends Component { } protected _conditionalDisableScrollBar (contentSize: Size, scrollViewSize: Size): boolean { - if (contentSize.width <= scrollViewSize.width && this._direction === Direction.HORIZONTAL) { + if (contentSize.width <= scrollViewSize.width && this._direction === ScrollBarDirection.HORIZONTAL) { return true; } - if (contentSize.height <= scrollViewSize.height && this._direction === Direction.VERTICAL) { + if (contentSize.height <= scrollViewSize.height && this._direction === ScrollBarDirection.VERTICAL) { return true; } return false; @@ -458,7 +458,7 @@ export class ScrollBar extends Component { } const position = (handleNodeMeasure - actualLenth) * positionRatio; - if (this._direction === Direction.VERTICAL) { + if (this._direction === ScrollBarDirection.VERTICAL) { out.set(0, position); } else { out.set(position, 0); @@ -475,7 +475,7 @@ export class ScrollBar extends Component { handleTrans.setAnchorPoint(defaultAnchor); } - if (this._direction === Direction.HORIZONTAL) { + if (this._direction === ScrollBarDirection.HORIZONTAL) { handleTrans.setContentSize(length, handleNodeSize.height); } else { handleTrans.setContentSize(handleNodeSize.width, length); diff --git a/cocos/ui/scroll-view.ts b/cocos/ui/scroll-view.ts index e55c809f439..c50eedd7f79 100644 --- a/cocos/ui/scroll-view.ts +++ b/cocos/ui/scroll-view.ts @@ -27,10 +27,10 @@ import { ccclass, displayOrder, executionOrder, help, menu, range, requireCompon import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { UITransform } from '../2d/framework'; import { legacyCC } from '../core/global-exports'; -import { Size, Vec2, Vec3, approx } from '../core/math'; +import { Size, Vec2, Vec3, approx, v2, v3 } from '../core/math'; import { errorID, logID } from '../core/platform/debug'; -import { Director, director } from '../game/director'; -import { Input, input } from '../input/input'; +import { director, DirectorEvent } from '../game/director'; +import { input } from '../input/input'; import { Event, EventGamepad, EventHandle, EventMouse, EventTouch, SystemEventType, Touch } from '../input/types'; import { EventHandler as ComponentEventHandler } from '../scene-graph/component-event-handler'; import { Node } from '../scene-graph/node'; @@ -40,16 +40,17 @@ import { DeviceType, XrUIPressEvent, XrUIPressEventType } from '../xr/event/xr-e import { Layout } from './layout'; import { ScrollBar } from './scroll-bar'; import { ViewGroup } from './view-group'; +import { InputEventType } from '../input/types/event-enum'; const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05; const EPSILON = 1e-4; const TOLERANCE = 1e4; const MOVEMENT_FACTOR = 0.7; -const _tempVec3 = new Vec3(); -const _tempVec3_1 = new Vec3(); -const _tempVec2 = new Vec2(); -const _tempVec2_1 = new Vec2(); +const _tempVec3 = v3(); +const _tempVec3_1 = v3(); +const _tempVec2 = v2(); +const _tempVec2_1 = v2(); const quintEaseOut = (time: number): number => { time -= 1; @@ -84,7 +85,7 @@ const eventMap = { * @zh * 滚动视图事件类型。 */ -export enum EventType { +export enum ScrollViewEventType { /** * @en * It means an invalid event type or "default empty value" of EventType. @@ -221,7 +222,7 @@ enum XrhoverType { @menu('UI/ScrollView') @requireComponent(UITransform) export class ScrollView extends ViewGroup { - public static EventType = EventType; + public static EventType = ScrollViewEventType; /** * @en @@ -987,7 +988,7 @@ export class ScrollView extends ViewGroup { // Because widget component will adjust content position and scrollView position is correct after visit // So this event could make sure the content is on the correct position after loading. if (this._content) { - director.once(Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); + director.once(DirectorEvent.BEFORE_DRAW, this._adjustContentOutOfBoundary, this); } } @@ -1049,8 +1050,8 @@ export class ScrollView extends ViewGroup { this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); - input.on(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this); - input.on(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); + input.on(InputEventType.HANDLE_INPUT, this._dispatchEventHandleInput, this); + input.on(InputEventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); } protected _unregisterEvent (): void { @@ -1062,8 +1063,8 @@ export class ScrollView extends ViewGroup { this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this); this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this); - input.off(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this); - input.off(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); + input.off(InputEventType.HANDLE_INPUT, this._dispatchEventHandleInput, this); + input.off(InputEventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this); } protected _onMouseWheel (event: EventMouse, captureListeners?: Node[]): void { @@ -1150,7 +1151,7 @@ export class ScrollView extends ViewGroup { return; } - this._dispatchEvent(EventType.TOUCH_UP); + this._dispatchEvent(ScrollViewEventType.TOUCH_UP); const touch = event.touch!; this._handleReleaseLogic(touch); @@ -1448,12 +1449,12 @@ export class ScrollView extends ViewGroup { } protected _dispatchEvent (event: string): void { - if (event === EventType.SCROLL_ENDED as string) { + if (event === ScrollViewEventType.SCROLL_ENDED as string) { this._scrollEventEmitMask = 0; - } else if (event === EventType.SCROLL_TO_TOP as string - || event === EventType.SCROLL_TO_BOTTOM as string - || event === EventType.SCROLL_TO_LEFT as string - || event === EventType.SCROLL_TO_RIGHT as string) { + } else if (event === ScrollViewEventType.SCROLL_TO_TOP as string + || event === ScrollViewEventType.SCROLL_TO_BOTTOM as string + || event === ScrollViewEventType.SCROLL_TO_LEFT as string + || event === ScrollViewEventType.SCROLL_TO_RIGHT as string) { const flag = 1 << eventMap[event]; if (this._scrollEventEmitMask & flag) { return; @@ -1540,7 +1541,7 @@ export class ScrollView extends ViewGroup { if (this._scrolling) { this._scrolling = false; if (!this._autoScrolling) { - this._dispatchEvent(EventType.SCROLL_ENDED); + this._dispatchEvent(ScrollViewEventType.SCROLL_ENDED); } } } @@ -1578,8 +1579,8 @@ export class ScrollView extends ViewGroup { realMove.add(outOfBoundary); } - let verticalScrollEventType: EventType = EventType.NONE; - let horizontalScrollEventType: EventType = EventType.NONE; + let verticalScrollEventType: ScrollViewEventType = ScrollViewEventType.NONE; + let horizontalScrollEventType: ScrollViewEventType = ScrollViewEventType.NONE; if (this._content) { const { anchorX, anchorY, width, height } = this._content._uiProps.uiTransformComp!; const pos = this._content.position || Vec3.ZERO; @@ -1589,13 +1590,13 @@ export class ScrollView extends ViewGroup { const icBottomPos = pos.y - anchorY * height; if (icBottomPos + realMove.y >= this._bottomBoundary) { - verticalScrollEventType = EventType.SCROLL_TO_BOTTOM; + verticalScrollEventType = ScrollViewEventType.SCROLL_TO_BOTTOM; } } else if (realMove.y < 0) { // down const icTopPos = pos.y - anchorY * height + height; if (icTopPos + realMove.y <= this._topBoundary) { - verticalScrollEventType = EventType.SCROLL_TO_TOP; + verticalScrollEventType = ScrollViewEventType.SCROLL_TO_TOP; } } } @@ -1604,12 +1605,12 @@ export class ScrollView extends ViewGroup { if (realMove.x < 0) { // left const icRightPos = pos.x - anchorX * width + width; if (icRightPos + realMove.x <= this._rightBoundary) { - horizontalScrollEventType = EventType.SCROLL_TO_RIGHT; + horizontalScrollEventType = ScrollViewEventType.SCROLL_TO_RIGHT; } } else if (realMove.x > 0) { // right const icLeftPos = pos.x - anchorX * width; if (icLeftPos + realMove.x >= this._leftBoundary) { - horizontalScrollEventType = EventType.SCROLL_TO_LEFT; + horizontalScrollEventType = ScrollViewEventType.SCROLL_TO_LEFT; } } } @@ -1620,22 +1621,22 @@ export class ScrollView extends ViewGroup { if ((this.horizontal && realMove.x !== 0) || (this.vertical && realMove.y !== 0)) { if (!this._scrolling) { this._scrolling = true; - this._dispatchEvent(EventType.SCROLL_BEGAN); + this._dispatchEvent(ScrollViewEventType.SCROLL_BEGAN); } - this._dispatchEvent(EventType.SCROLLING); + this._dispatchEvent(ScrollViewEventType.SCROLLING); } - if (verticalScrollEventType !== EventType.NONE) { + if (verticalScrollEventType !== ScrollViewEventType.NONE) { this._dispatchEvent(verticalScrollEventType); } - if (horizontalScrollEventType !== EventType.NONE) { + if (horizontalScrollEventType !== ScrollViewEventType.NONE) { this._dispatchEvent(horizontalScrollEventType); } } protected _handlePressLogic (): void { if (this._autoScrolling) { - this._dispatchEvent(EventType.SCROLL_ENDED); + this._dispatchEvent(ScrollViewEventType.SCROLL_ENDED); } this._autoScrolling = false; @@ -1694,16 +1695,16 @@ export class ScrollView extends ViewGroup { if (!this._isBouncing) { if (bounceBackAmount.y > 0) { - this._dispatchEvent(EventType.BOUNCE_TOP); + this._dispatchEvent(ScrollViewEventType.BOUNCE_TOP); } if (bounceBackAmount.y < 0) { - this._dispatchEvent(EventType.BOUNCE_BOTTOM); + this._dispatchEvent(ScrollViewEventType.BOUNCE_BOTTOM); } if (bounceBackAmount.x > 0) { - this._dispatchEvent(EventType.BOUNCE_RIGHT); + this._dispatchEvent(ScrollViewEventType.BOUNCE_RIGHT); } if (bounceBackAmount.x < 0) { - this._dispatchEvent(EventType.BOUNCE_LEFT); + this._dispatchEvent(ScrollViewEventType.BOUNCE_LEFT); } this._isBouncing = true; } @@ -1765,7 +1766,7 @@ export class ScrollView extends ViewGroup { const fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming(); if (fireEvent && !this._isScrollEndedWithThresholdEventFired) { - this._dispatchEvent(EventType.SCROLL_ENG_WITH_THRESHOLD); + this._dispatchEvent(ScrollViewEventType.SCROLL_ENG_WITH_THRESHOLD); this._isScrollEndedWithThresholdEventFired = true; } @@ -1795,12 +1796,12 @@ export class ScrollView extends ViewGroup { deltaMove.subtract(this._getContentPosition()); this._clampDelta(deltaMove); this._moveContent(deltaMove, reachedEnd); - this._dispatchEvent(EventType.SCROLLING); + this._dispatchEvent(ScrollViewEventType.SCROLLING); if (!this._autoScrolling) { this._isBouncing = false; this._scrolling = false; - this._dispatchEvent(EventType.SCROLL_ENDED); + this._dispatchEvent(ScrollViewEventType.SCROLL_ENDED); } } @@ -1813,7 +1814,7 @@ export class ScrollView extends ViewGroup { if (this._scrolling) { this._scrolling = false; if (!this._autoScrolling) { - this._dispatchEvent(EventType.SCROLL_ENDED); + this._dispatchEvent(ScrollViewEventType.SCROLL_ENDED); } } this.unschedule(this._checkMouseWheel); @@ -1829,7 +1830,7 @@ export class ScrollView extends ViewGroup { if (this._scrolling) { this._scrolling = false; if (!this._autoScrolling) { - this._dispatchEvent(EventType.SCROLL_ENDED); + this._dispatchEvent(ScrollViewEventType.SCROLL_ENDED); } } this.unschedule(this._checkMouseWheel); diff --git a/cocos/ui/sub-context-view.ts b/cocos/ui/sub-context-view.ts index e2cac9207f9..4657339dded 100644 --- a/cocos/ui/sub-context-view.ts +++ b/cocos/ui/sub-context-view.ts @@ -101,51 +101,51 @@ export class SubContextView extends Component { return; } this._fps = value; - this._updateInterval = 1000 / value; + this._updateInterval$ = 1000 / value; } @serializable private _fps = 60; - private _sprite: Sprite | null = null; - private _imageAsset: ImageAsset = new ImageAsset(); - private _texture: Texture2D = new Texture2D(); - private _updatedTime = 0; - private _updateInterval = 0; - private _openDataContext: any = null; - private _content: Node = new Node('content'); + private _sprite$: Sprite | null = null; + private _imageAsset$: ImageAsset = new ImageAsset(); + private _texture$: Texture2D = new Texture2D(); + private _updatedTime$ = 0; + private _updateInterval$ = 0; + private _openDataContext$: any = null; + private _content$: Node = new Node('content'); @serializable private _designResolutionSize: Size = new Size(640, 960); constructor () { super(); - this._content.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy; - this._updatedTime = performance.now(); + this._content$.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy; + this._updatedTime$ = performance.now(); } public onLoad (): void { if (minigame.getOpenDataContext) { - this._updateInterval = 1000 / this._fps; - this._openDataContext = minigame.getOpenDataContext(); - this._initSharedCanvas(); - this._initContentNode(); - this._updateSubContextView(); - this._updateContentLayer(); + this._updateInterval$ = 1000 / this._fps; + this._openDataContext$ = minigame.getOpenDataContext(); + this._initSharedCanvas$(); + this._initContentNode$(); + this._updateSubContextView$(); + this._updateContentLayer$(); } else { this.enabled = false; } } public onEnable (): void { - this._registerNodeEvent(); + this._registerNodeEvent$(); } public onDisable (): void { - this._unregisterNodeEvent(); + this._unregisterNodeEvent$(); } - private _initSharedCanvas (): void { - if (this._openDataContext) { - const sharedCanvas = this._openDataContext.canvas; + private _initSharedCanvas$ (): void { + if (this._openDataContext$) { + const sharedCanvas = this._openDataContext$.canvas; let designWidth = this._designResolutionSize.width; let designHeight = this._designResolutionSize.height; if (WECHAT || WECHAT_MINI_PROGRAM) { @@ -165,41 +165,41 @@ export class SubContextView extends Component { } } - private _initContentNode (): void { - if (this._openDataContext) { - const sharedCanvas = this._openDataContext.canvas; + private _initContentNode$ (): void { + if (this._openDataContext$) { + const sharedCanvas = this._openDataContext$.canvas; - const image = this._imageAsset; + const image = this._imageAsset$; image.reset(sharedCanvas); - this._texture.image = image; - this._texture.create(sharedCanvas.width, sharedCanvas.height); + this._texture$.image = image; + this._texture$.create(sharedCanvas.width, sharedCanvas.height); - this._sprite = this._content.getComponent(Sprite); - if (!this._sprite) { - this._sprite = this._content.addComponent(Sprite); + this._sprite$ = this._content$.getComponent(Sprite); + if (!this._sprite$) { + this._sprite$ = this._content$.addComponent(Sprite); } - if (this._sprite.spriteFrame) { - this._sprite.spriteFrame.texture = this._texture; + if (this._sprite$.spriteFrame) { + this._sprite$.spriteFrame.texture = this._texture$; } else { const sp = new SpriteFrame(); - sp.texture = this._texture; - this._sprite.spriteFrame = sp; + sp.texture = this._texture$; + this._sprite$.spriteFrame = sp; } - this._content.parent = this.node; + this._content$.parent = this.node; } } - private _updateSubContextView (): void { - if (!this._openDataContext) { + private _updateSubContextView$ (): void { + if (!this._openDataContext$) { return; } // update subContextView size // use SHOW_ALL policy to adapt subContextView const nodeTrans = this.node.getComponent(UITransform) as UITransform; - const contentTrans = this._content.getComponent(UITransform) as UITransform; + const contentTrans = this._content$.getComponent(UITransform) as UITransform; const scaleX = nodeTrans.width / contentTrans.width; const scaleY = nodeTrans.height / contentTrans.height; @@ -219,7 +219,7 @@ export class SubContextView extends Component { const width = viewportRect.width * (box.width / visibleSize.width) / dpr; const height = viewportRect.height * (box.height / visibleSize.height) / dpr; - this._openDataContext.postMessage({ + this._openDataContext$.postMessage({ fromEngine: true, // compatible deprecated property type: 'engine', event: 'viewport', @@ -230,9 +230,9 @@ export class SubContextView extends Component { }); } - private _updateSubContextTexture (): void { - const img = this._imageAsset; - if (!img || !this._openDataContext) { + private _updateSubContextTexture$ (): void { + const img = this._imageAsset$; + if (!img || !this._openDataContext$) { return; } @@ -240,51 +240,51 @@ export class SubContextView extends Component { return; } - const sharedCanvas = this._openDataContext.canvas; + const sharedCanvas = this._openDataContext$.canvas; img.reset(sharedCanvas); if (sharedCanvas.width > img.width || sharedCanvas.height > img.height) { - this._texture.create(sharedCanvas.width, sharedCanvas.height); + this._texture$.create(sharedCanvas.width, sharedCanvas.height); } - this._texture.uploadData(sharedCanvas); + this._texture$.uploadData(sharedCanvas); } - private _registerNodeEvent (): void { - this.node.on(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this); - this.node.on(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this); - this.node.on(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this); + private _registerNodeEvent$ (): void { + this.node.on(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView$, this); + this.node.on(NodeEventType.SIZE_CHANGED, this._updateSubContextView$, this); + this.node.on(NodeEventType.LAYER_CHANGED, this._updateContentLayer$, this); } - private _unregisterNodeEvent (): void { - this.node.off(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this); - this.node.off(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this); - this.node.off(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this); + private _unregisterNodeEvent$ (): void { + this.node.off(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView$, this); + this.node.off(NodeEventType.SIZE_CHANGED, this._updateSubContextView$, this); + this.node.off(NodeEventType.LAYER_CHANGED, this._updateContentLayer$, this); } - private _updateContentLayer (): void { - this._content.layer = this.node.layer; + private _updateContentLayer$ (): void { + this._content$.layer = this.node.layer; } public update (dt?: number): void { const calledUpdateManually = (dt === undefined); if (calledUpdateManually) { - this._updateSubContextTexture(); + this._updateSubContextTexture$(); return; } const now = performance.now(); - const deltaTime = (now - this._updatedTime); - if (deltaTime >= this._updateInterval) { - this._updatedTime += this._updateInterval; - this._updateSubContextTexture(); + const deltaTime = (now - this._updatedTime$); + if (deltaTime >= this._updateInterval$) { + this._updatedTime$ += this._updateInterval$; + this._updateSubContextTexture$(); } } public onDestroy (): void { - this._content.destroy(); - this._texture.destroy(); - if (this._sprite) { this._sprite.destroy(); } - this._imageAsset.destroy(); - this._openDataContext = null; + this._content$.destroy(); + this._texture$.destroy(); + if (this._sprite$) { this._sprite$.destroy(); } + this._imageAsset$.destroy(); + this._openDataContext$ = null; } } diff --git a/cocos/ui/toggle.ts b/cocos/ui/toggle.ts index f680e301e24..cfe483957da 100644 --- a/cocos/ui/toggle.ts +++ b/cocos/ui/toggle.ts @@ -30,10 +30,10 @@ import { UITransform } from '../2d/framework'; import { Sprite } from '../2d/components/sprite'; import { ToggleContainer } from './toggle-container'; import { extendsEnum } from '../core/data/utils/extends-enum'; -import { EventType as ButtonEventType, Button } from './button'; +import { ButtonEventType, Button } from './button'; import { legacyCC } from '../core/global-exports'; -enum EventType { +enum ToggleEventType { TOGGLE = 'toggle', } @@ -115,7 +115,7 @@ export class Toggle extends Button { * @en Enum for toggle event. * @zh toggle 事件枚举。 */ - public static EventType = extendsEnum(EventType, ButtonEventType); + public static EventType = extendsEnum(ToggleEventType, ButtonEventType); /** * @en diff --git a/cocos/ui/view.ts b/cocos/ui/view.ts index 23f41ba8e72..d4d2266fe2c 100644 --- a/cocos/ui/view.ts +++ b/cocos/ui/view.ts @@ -33,7 +33,7 @@ import { rect, Rect, size, Size, Vec2 } from '../core/math'; import { visibleRect, cclegacy, errorID, screen, macro, System, assert } from '../core'; import { Orientation } from '../../pal/screen-adapter/enum-type'; import { director } from '../game/director'; -import { Settings, settings } from '../core/settings'; +import { settings, SettingsCategory } from '../core/settings'; /** * @en View represents the game window.
@@ -67,20 +67,20 @@ export class View extends Eventify(System) { */ public _designResolutionSize: Size = size(0, 0); // resolution size, it is the size appropriate for the app resources. - private _scaleX: number = 1; - private _scaleY: number = 1; - private _viewportRect: Rect = rect(); // Viewport is the container's rect related to content's coordinates in pixel - private _visibleRect: Rect = rect(); // The visible rect in content's coordinate in point - private _autoFullScreen: boolean = false; // Auto full screen disabled by default - private _retinaEnabled: boolean = false; // Retina disabled by default - private _resizeCallback: (() => void) | null = null; // Custom callback for resize event - private declare _resolutionPolicy: ResolutionPolicy; - - private declare _rpExactFit: ResolutionPolicy; - private declare _rpShowAll: ResolutionPolicy; - private declare _rpNoBorder: ResolutionPolicy; - private declare _rpFixedHeight: ResolutionPolicy; - private declare _rpFixedWidth: ResolutionPolicy; + private _scaleX$: number = 1; + private _scaleY$: number = 1; + private _viewportRect$: Rect = rect(); // Viewport is the container's rect related to content's coordinates in pixel + private _visibleRect$: Rect = rect(); // The visible rect in content's coordinate in point + private _autoFullScreen$: boolean = false; // Auto full screen disabled by default + private _retinaEnabled$: boolean = false; // Retina disabled by default + private _resizeCallback$: (() => void) | null = null; // Custom callback for resize event + private declare _resolutionPolicy$: ResolutionPolicy; + + private declare _rpExactFit$: ResolutionPolicy; + private declare _rpShowAll$: ResolutionPolicy; + private declare _rpNoBorder$: ResolutionPolicy; + private declare _rpFixedHeight$: ResolutionPolicy; + private declare _rpFixedWidth$: ResolutionPolicy; constructor () { super(); @@ -89,12 +89,12 @@ export class View extends Eventify(System) { const _strategy = ContentStrategy; // Setup system default resolution policies - this._rpExactFit = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT); - this._rpShowAll = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL); - this._rpNoBorder = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER); - this._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT); - this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); - this._resolutionPolicy = this._rpShowAll; + this._rpExactFit$ = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT); + this._rpShowAll$ = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL); + this._rpNoBorder$ = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER); + this._rpFixedHeight$ = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT); + this._rpFixedWidth$ = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); + this._resolutionPolicy$ = this._rpShowAll$; } // Call init at the time Game.EVENT_ENGINE_INITED @@ -104,20 +104,20 @@ export class View extends Eventify(System) { const h = windowSize.height; this._designResolutionSize.width = w; this._designResolutionSize.height = h; - this._viewportRect.width = w; - this._viewportRect.height = h; - this._visibleRect.width = w; - this._visibleRect.height = h; + this._viewportRect$.width = w; + this._viewportRect$.height = h; + this._visibleRect$.width = w; + this._visibleRect$.height = h; - localWinSize.width = this._visibleRect.width; - localWinSize.height = this._visibleRect.height; + localWinSize.width = this._visibleRect$.width; + localWinSize.height = this._visibleRect$.height; if (visibleRect) { - visibleRect.init(this._visibleRect); + visibleRect.init(this._visibleRect$); } if (!EDITOR) { this.resizeWithBrowserSize(true); - const designResolution = settings.querySettings(Settings.Category.SCREEN, 'designResolution'); + const designResolution = settings.querySettings(SettingsCategory.SCREEN, 'designResolution'); if (designResolution) { this.setDesignResolutionSize( Number(designResolution.width), @@ -128,8 +128,8 @@ export class View extends Eventify(System) { } // For now, the engine UI is adapted to resolution size, instead of window size. - screen.on('window-resize', this._updateAdaptResult, this); - screen.on('fullscreen-change', this._updateAdaptResult, this); + screen.on('window-resize', this._updateAdaptResult$, this); + screen.on('fullscreen-change', this._updateAdaptResult$, this); } /** @@ -160,7 +160,7 @@ export class View extends Eventify(System) { */ public setResizeCallback (callback: (() => void) | null): void { if (typeof callback === 'function' || callback == null) { - this._resizeCallback = callback; + this._resizeCallback$ = callback; } } @@ -211,7 +211,7 @@ export class View extends Eventify(System) { * @deprecated since v3.4.0 */ public enableRetina (enabled: boolean): void { - this._retinaEnabled = !!enabled; + this._retinaEnabled$ = !!enabled; } /** @@ -224,7 +224,7 @@ export class View extends Eventify(System) { * @deprecated since v3.4.0 */ public isRetinaEnabled (): boolean { - return this._retinaEnabled; + return this._retinaEnabled$; } /** @@ -239,10 +239,10 @@ export class View extends Eventify(System) { * @deprecated since v3.3, please use screen.requestFullScreen() instead. */ public enableAutoFullScreen (enabled: boolean): void { - if (enabled === this._autoFullScreen) { + if (enabled === this._autoFullScreen$) { return; } - this._autoFullScreen = enabled; + this._autoFullScreen$ = enabled; if (enabled) { screen.requestFullScreen().catch((e) => { // do nothing @@ -261,7 +261,7 @@ export class View extends Eventify(System) { * @deprecated since v3.3 */ public isAutoFullScreenEnabled (): boolean { - return this._autoFullScreen; + return this._autoFullScreen$; } /** @@ -341,7 +341,7 @@ export class View extends Eventify(System) { * @zh 返回视图窗口可见区域尺寸。 */ public getVisibleSize (): Size { - return new Size(this._visibleRect.width, this._visibleRect.height); + return new Size(this._visibleRect$.width, this._visibleRect$.height); } /** @@ -350,8 +350,8 @@ export class View extends Eventify(System) { */ public getVisibleSizeInPixel (): Size { return new Size( - this._visibleRect.width * this._scaleX, - this._visibleRect.height * this._scaleY, + this._visibleRect$.width * this._scaleX$, + this._visibleRect$.height * this._scaleY$, ); } @@ -360,7 +360,7 @@ export class View extends Eventify(System) { * @zh 返回视图窗口可见区域原点。 */ public getVisibleOrigin (): Vec2 { - return new Vec2(this._visibleRect.x, this._visibleRect.y); + return new Vec2(this._visibleRect$.x, this._visibleRect$.y); } /** @@ -369,8 +369,8 @@ export class View extends Eventify(System) { */ public getVisibleOriginInPixel (): Vec2 { return new Vec2( - this._visibleRect.x * this._scaleX, - this._visibleRect.y * this._scaleY, + this._visibleRect$.x * this._scaleX$, + this._visibleRect$.y * this._scaleY$, ); } @@ -380,29 +380,29 @@ export class View extends Eventify(System) { * @see [[ResolutionPolicy]] */ public getResolutionPolicy (): ResolutionPolicy { - return this._resolutionPolicy; + return this._resolutionPolicy$; } private _updateResolutionPolicy (resolutionPolicy: ResolutionPolicy|number): void { if (resolutionPolicy instanceof ResolutionPolicy) { - this._resolutionPolicy = resolutionPolicy; + this._resolutionPolicy$ = resolutionPolicy; } else { // Ensure compatibility with JSB const _locPolicy = ResolutionPolicy; if (resolutionPolicy === _locPolicy.EXACT_FIT) { - this._resolutionPolicy = this._rpExactFit; + this._resolutionPolicy$ = this._rpExactFit$; } if (resolutionPolicy === _locPolicy.SHOW_ALL) { - this._resolutionPolicy = this._rpShowAll; + this._resolutionPolicy$ = this._rpShowAll$; } if (resolutionPolicy === _locPolicy.NO_BORDER) { - this._resolutionPolicy = this._rpNoBorder; + this._resolutionPolicy$ = this._rpNoBorder$; } if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) { - this._resolutionPolicy = this._rpFixedHeight; + this._resolutionPolicy$ = this._rpFixedHeight$; } if (resolutionPolicy === _locPolicy.FIXED_WIDTH) { - this._resolutionPolicy = this._rpFixedWidth; + this._resolutionPolicy$ = this._rpFixedWidth$; } } } @@ -439,7 +439,7 @@ export class View extends Eventify(System) { } this._updateResolutionPolicy(resolutionPolicy); - const policy = this._resolutionPolicy; + const policy = this._resolutionPolicy$; if (policy) { policy.preApply(this); } @@ -450,13 +450,13 @@ export class View extends Eventify(System) { const result = policy.apply(this, this._designResolutionSize); if (result.scale && result.scale.length === 2) { - this._scaleX = result.scale[0]; - this._scaleY = result.scale[1]; + this._scaleX$ = result.scale[0]; + this._scaleY$ = result.scale[1]; } if (result.viewport) { - const vp = this._viewportRect; - const vb = this._visibleRect; + const vp = this._viewportRect$; + const vb = this._visibleRect$; const rv = result.viewport; vp.x = rv.x; @@ -466,16 +466,16 @@ export class View extends Eventify(System) { vb.x = 0; vb.y = 0; - vb.width = rv.width / this._scaleX; - vb.height = rv.height / this._scaleY; + vb.width = rv.width / this._scaleX$; + vb.height = rv.height / this._scaleY$; } policy.postApply(this); - localWinSize.width = this._visibleRect.width; - localWinSize.height = this._visibleRect.height; + localWinSize.width = this._visibleRect$.width; + localWinSize.height = this._visibleRect$.height; if (visibleRect) { - visibleRect.init(this._visibleRect); + visibleRect.init(this._visibleRect$); } this.emit('design-resolution-changed'); @@ -524,7 +524,7 @@ export class View extends Eventify(System) { * @zh 返回视窗剪裁区域。 */ public getViewportRect (): Rect { - return this._viewportRect; + return this._viewportRect$; } /** @@ -532,7 +532,7 @@ export class View extends Eventify(System) { * @zh 返回横轴的缩放比,这个缩放比是将画布像素分辨率放到设计分辨率的比例。 */ public getScaleX (): number { - return this._scaleX; + return this._scaleX$; } /** @@ -540,7 +540,7 @@ export class View extends Eventify(System) { * @zh 返回纵轴的缩放比,这个缩放比是将画布像素分辨率缩放到设计分辨率的比例。 */ public getScaleY (): number { - return this._scaleY; + return this._scaleY$; } /** @@ -578,12 +578,12 @@ export class View extends Eventify(System) { // Convert location in Cocos screen coordinate to location in UI space private _convertToUISpace (point): void { - const viewport = this._viewportRect; - point.x = (point.x - viewport.x) / this._scaleX; - point.y = (point.y - viewport.y) / this._scaleY; + const viewport = this._viewportRect$; + point.x = (point.x - viewport.x) / this._scaleX$; + point.y = (point.y - viewport.y) / this._scaleY$; } - private _updateAdaptResult (width: number, height: number, windowId?: number): void { + private _updateAdaptResult$ (width: number, height: number, windowId?: number): void { // The default invalid windowId is 0 cclegacy.director.root.resize(width, height, (windowId === undefined || windowId === 0) ? 1 : windowId); // Frame size changed, do resize works @@ -591,13 +591,13 @@ export class View extends Eventify(System) { const h = this._designResolutionSize.height; if (width > 0 && height > 0) { - this.setDesignResolutionSize(w, h, this._resolutionPolicy); + this.setDesignResolutionSize(w, h, this._resolutionPolicy$); } else { assert(false, '_updateAdaptResult Invalid size.'); } this.emit('canvas-resize'); - this._resizeCallback?.(); + this._resizeCallback$?.(); } } @@ -639,7 +639,7 @@ class ContainerStrategy { * @param view * @param designedResolution */ - public apply (_view: View, designedResolution: Size): void { + public apply$ (_view: View, designedResolution: Size): void { // do nothing } @@ -709,7 +709,7 @@ class ContentStrategy { * @zh 策略应用前的操作 * @param view - The target view */ - public preApply (_view: View): void { + public preApply$ (_view: View): void { // do nothing } @@ -720,7 +720,7 @@ class ContentStrategy { * @zh 调用策略方法 * @return The result scale and viewport rect */ - public apply (_view: View, designedResolution: Size): AdaptResult { + public apply$ (_view: View, designedResolution: Size): AdaptResult { return { scale: [1, 1] }; } @@ -729,14 +729,14 @@ class ContentStrategy { * @zh 策略调用之后的操作 * @param view - The target view */ - public postApply (_view: View): void { + public postApply$ (_view: View): void { // do nothing } /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _buildResult (containerW: number, containerH: number, contentW: number, contentH: number, scaleX: number, scaleY: number): AdaptResult { + public _buildResult$ (containerW: number, containerH: number, contentW: number, contentH: number, scaleX: number, scaleY: number): AdaptResult { // Makes content fit better the canvas if (Math.abs(containerW - contentW) < 2) { contentW = containerW; @@ -771,7 +771,7 @@ class EqualToFrame extends ContainerStrategy { super(); } - public apply (_view, designedResolution): void { + public apply$ (_view, designedResolution): void { screenAdapter.isProportionalToFrame = false; this._setupCanvas(); } @@ -787,7 +787,7 @@ class ProportionalToFrame extends ContainerStrategy { super(); } - public apply (_view, designedResolution): void { + public apply$ (_view, designedResolution): void { screenAdapter.isProportionalToFrame = true; this._setupCanvas(); } @@ -807,14 +807,14 @@ class ExactFit extends ContentStrategy { this._strategy = ResolutionPolicy.EXACT_FIT; } - public apply (_view: View, designedResolution: Size): AdaptResult { + public apply$ (_view: View, designedResolution: Size): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; const scaleX = containerW / designedResolution.width; const scaleY = containerH / designedResolution.height; - return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY); + return this._buildResult$(containerW, containerH, containerW, containerH, scaleX, scaleY); } } @@ -826,7 +826,7 @@ class ShowAll extends ContentStrategy { this._strategy = ResolutionPolicy.SHOW_ALL; } - public apply (_view, designedResolution): AdaptResult { + public apply$ (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -848,7 +848,7 @@ class ShowAll extends ContentStrategy { contentH = containerH; } - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + return this._buildResult$(containerW, containerH, contentW, contentH, scale, scale); } } @@ -860,7 +860,7 @@ class NoBorder extends ContentStrategy { this._strategy = ResolutionPolicy.NO_BORDER; } - public apply (_view, designedResolution): AdaptResult { + public apply$ (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -882,7 +882,7 @@ class NoBorder extends ContentStrategy { contentH = designH * scale; } - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + return this._buildResult$(containerW, containerH, contentW, contentH, scale, scale); } } @@ -894,7 +894,7 @@ class FixedHeight extends ContentStrategy { this._strategy = ResolutionPolicy.FIXED_HEIGHT; } - public apply (_view, designedResolution): AdaptResult { + public apply$ (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -903,7 +903,7 @@ class FixedHeight extends ContentStrategy { const contentW = containerW; const contentH = containerH; - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + return this._buildResult$(containerW, containerH, contentW, contentH, scale, scale); } } @@ -915,7 +915,7 @@ class FixedWidth extends ContentStrategy { this._strategy = ResolutionPolicy.FIXED_WIDTH; } - public apply (_view, designedResolution): AdaptResult { + public apply$ (_view, designedResolution): AdaptResult { const windowSize = screen.windowSize; const containerW = windowSize.width; const containerH = windowSize.height; @@ -924,7 +924,7 @@ class FixedWidth extends ContentStrategy { const contentW = containerW; const contentH = containerH; - return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); + return this._buildResult$(containerW, containerH, contentW, contentH, scale, scale); } } @@ -990,8 +990,8 @@ export class ResolutionPolicy { public name = 'ResolutionPolicy'; - private declare _containerStrategy: ContainerStrategy; - private declare _contentStrategy: ContentStrategy; + private declare _containerStrategy$: ContainerStrategy; + private declare _contentStrategy$: ContentStrategy; /** * Constructor of ResolutionPolicy @@ -999,8 +999,8 @@ export class ResolutionPolicy { * @param contentStg */ constructor (containerStg: ContainerStrategy, contentStg: ContentStrategy) { - this._containerStrategy = containerStg; - this._contentStrategy = contentStg; + this._containerStrategy$ = containerStg; + this._contentStrategy$ = contentStg; } get canvasSize (): Size { @@ -1013,7 +1013,7 @@ export class ResolutionPolicy { * @param _view The target view */ public preApply (_view: View): void { - this._contentStrategy.preApply(_view); + this._contentStrategy$.preApply$(_view); } /** @@ -1026,8 +1026,8 @@ export class ResolutionPolicy { * @return An object contains the scale X/Y values and the viewport rect */ public apply (_view: View, designedResolution: Size): AdaptResult { - this._containerStrategy.apply(_view, designedResolution); - return this._contentStrategy.apply(_view, designedResolution); + this._containerStrategy$.apply$(_view, designedResolution); + return this._contentStrategy$.apply$(_view, designedResolution); } /** @@ -1036,7 +1036,7 @@ export class ResolutionPolicy { * @param _view - The target view */ public postApply (_view: View): void { - this._contentStrategy.postApply(_view); + this._contentStrategy$.postApply$(_view); } /** @@ -1045,7 +1045,7 @@ export class ResolutionPolicy { * @param containerStg The container strategy */ public setContainerStrategy (containerStg: ContainerStrategy): void { - this._containerStrategy = containerStg; + this._containerStrategy$ = containerStg; } /** @@ -1054,7 +1054,7 @@ export class ResolutionPolicy { * @param contentStg The content strategy */ public setContentStrategy (contentStg: ContentStrategy): void { - this._contentStrategy = contentStg; + this._contentStrategy$ = contentStg; } /** @@ -1063,7 +1063,7 @@ export class ResolutionPolicy { * @returns ContentStrategy instance. */ public getContentStrategy (): ContentStrategy { - return this._contentStrategy; + return this._contentStrategy$; } } cclegacy.ResolutionPolicy = ResolutionPolicy; diff --git a/cocos/ui/widget-manager.ts b/cocos/ui/widget-manager.ts index f5a9f732a5a..9eb65063a9b 100644 --- a/cocos/ui/widget-manager.ts +++ b/cocos/ui/widget-manager.ts @@ -25,7 +25,7 @@ import { EDITOR, DEV } from 'internal:constants'; import { screenAdapter } from 'pal/screen-adapter'; -import { Director, director } from '../game/director'; +import { director, DirectorEvent } from '../game/director'; import { Vec2, Vec3, visibleRect, js, cclegacy, approx, EPSILON } from '../core'; import { View } from './view'; import { Scene } from '../scene-graph'; @@ -288,8 +288,8 @@ export const widgetManager = cclegacy._widgetManager = { } : null, init (): void { - director.on(Director.EVENT_AFTER_SCENE_LAUNCH, refreshScene); - director.on(Director.EVENT_AFTER_UPDATE, refreshScene); + director.on(DirectorEvent.AFTER_SCENE_LAUNCH, refreshScene); + director.on(DirectorEvent.AFTER_UPDATE, refreshScene); View.instance.on('design-resolution-changed', this.onResized, this); if (!EDITOR) { @@ -410,6 +410,6 @@ export const widgetManager = cclegacy._widgetManager = { AlignFlags, }; -director.on(Director.EVENT_INIT, () => { +director.on(DirectorEvent.INIT, () => { widgetManager.init(); }); diff --git a/cocos/video/video-player-enums.ts b/cocos/video/video-player-enums.ts index 21c5fc0ad57..d2b0b8b2e19 100644 --- a/cocos/video/video-player-enums.ts +++ b/cocos/video/video-player-enums.ts @@ -45,7 +45,7 @@ export const ResourceType = Enum({ LOCAL: 1, }); -export enum EventType { +export enum VideoPlayerEventType { /** * @en None. * @zh 无。 diff --git a/cocos/video/video-player-impl-web.ts b/cocos/video/video-player-impl-web.ts index 0df7831777a..72e6f374464 100644 --- a/cocos/video/video-player-impl-web.ts +++ b/cocos/video/video-player-impl-web.ts @@ -27,7 +27,7 @@ import { mat4, visibleRect } from '../core'; import { sys, screen, warn } from '../core/platform'; import { game } from '../game'; import { contains } from '../core/utils/misc'; -import { EventType, READY_STATE } from './video-player-enums'; +import { VideoPlayerEventType, READY_STATE } from './video-player-enums'; import { VideoPlayerImpl } from './video-player-impl'; import { ClearFlagBit } from '../gfx'; import { BrowserType, OS } from '../../pal/system-info/enum-type'; @@ -103,7 +103,7 @@ export class VideoPlayerImplWeb extends VideoPlayerImpl { this._cachedCurrentTime = 0; setTimeout(() => { this._ignorePause = false; - this.dispatchEvent(EventType.STOPPED); + this.dispatchEvent(VideoPlayerEventType.STOPPED); }, 0); } } diff --git a/cocos/video/video-player-impl.ts b/cocos/video/video-player-impl.ts index cc9a4ba7d64..235ec8576fe 100644 --- a/cocos/video/video-player-impl.ts +++ b/cocos/video/video-player-impl.ts @@ -25,7 +25,7 @@ import { legacyCC } from '../core/global-exports'; import { UITransform } from '../2d/framework'; import { VideoPlayer } from './video-player'; -import { EventType } from './video-player-enums'; +import { VideoPlayerEventType } from './video-player-enums'; import { error } from '../core/platform'; import { director } from '../game/director'; import { Node } from '../scene-graph'; @@ -33,7 +33,7 @@ import type { Camera } from '../render-scene/scene'; export abstract class VideoPlayerImpl { protected _componentEventList: Map void> = new Map(); - protected _state = EventType.NONE; + protected _state = VideoPlayerEventType.NONE; protected _video: HTMLVideoElement | null = null; protected _onInterruptedBegin: () => void; @@ -76,7 +76,7 @@ export abstract class VideoPlayerImpl { this._node = component.node; this._uiTrans = component.node.getComponent(UITransform); this._onInterruptedBegin = (): void => { - if (!this.video || this._state !== EventType.PLAYING) { return; } + if (!this.video || this._state !== VideoPlayerEventType.PLAYING) { return; } this.video.pause(); this._interrupted = true; }; @@ -124,7 +124,7 @@ export abstract class VideoPlayerImpl { public get loaded (): boolean { return this._loaded; } public get componentEventList (): Map void> { return this._componentEventList; } public get video (): HTMLVideoElement | null { return this._video; } - public get state (): EventType { return this._state; } + public get state (): VideoPlayerEventType { return this._state; } public get isPlaying (): boolean { return this._playing; } get UICamera (): Camera | null { return director.root!.batcher2D.getFirstRenderCamera(this._node!); @@ -139,7 +139,7 @@ export abstract class VideoPlayerImpl { } else { this.disable(); } - this.dispatchEvent(EventType.META_LOADED); + this.dispatchEvent(VideoPlayerEventType.META_LOADED); const video = e.target as HTMLVideoElement; if (this._keepAspectRatio && video) { this.syncUITransform(video.videoWidth, video.videoHeight); @@ -150,16 +150,16 @@ export abstract class VideoPlayerImpl { public onCanPlay (e: Event): void { this._loaded = true; - this.dispatchEvent(EventType.READY_TO_PLAY); + this.dispatchEvent(VideoPlayerEventType.READY_TO_PLAY); } public onPlay (e: Event): void { this._playing = true; - this.dispatchEvent(EventType.PLAYING); + this.dispatchEvent(VideoPlayerEventType.PLAYING); } public onPlaying (e: Event): void { - this.dispatchEvent(EventType.PLAYING); + this.dispatchEvent(VideoPlayerEventType.PLAYING); } public onPause (e: Event): void { @@ -168,26 +168,26 @@ export abstract class VideoPlayerImpl { this._ignorePause = false; return; } - this.dispatchEvent(EventType.PAUSED); + this.dispatchEvent(VideoPlayerEventType.PAUSED); } public onStoped (e: Event): void { this._playing = false; this._ignorePause = false; - this.dispatchEvent(EventType.STOPPED); + this.dispatchEvent(VideoPlayerEventType.STOPPED); } public onEnded (e: Event): void { this._playing = false; - this.dispatchEvent(EventType.COMPLETED); + this.dispatchEvent(VideoPlayerEventType.COMPLETED); } public onClick (e: Event): void { - this.dispatchEvent(EventType.CLICKED); + this.dispatchEvent(VideoPlayerEventType.CLICKED); } public onError (e: Event): void { - this.dispatchEvent(EventType.ERROR); + this.dispatchEvent(VideoPlayerEventType.ERROR); const video = e.target as HTMLVideoElement; if (video && video.error) { error(`Error ${video.error.code}; details: ${video.error.message}`); diff --git a/cocos/video/video-player.ts b/cocos/video/video-player.ts index f441585075e..1bbf1f2e489 100644 --- a/cocos/video/video-player.ts +++ b/cocos/video/video-player.ts @@ -30,7 +30,7 @@ import { UITransform } from '../2d/framework'; import { clamp } from '../core/math'; import { VideoClip } from './assets/video-clip'; import { VideoPlayerImplManager } from './video-player-impl-manager'; -import { EventType, ResourceType } from './video-player-enums'; +import { VideoPlayerEventType, ResourceType } from './video-player-enums'; import { legacyCC } from '../core/global-exports'; import { VideoPlayerImplWeb } from './video-player-impl-web'; @@ -283,7 +283,7 @@ export class VideoPlayer extends Component { } } - public static EventType = EventType; + public static EventType = VideoPlayerEventType; public static ResourceType = ResourceType; /** @@ -351,8 +351,8 @@ export class VideoPlayer extends Component { * @zh * 获取当前视频状态。 */ - get state (): EventType { - if (!this._impl) { return EventType.NONE; } + get state (): VideoPlayerEventType { + if (!this._impl) { return VideoPlayerEventType.NONE; } return this._impl.state; } @@ -393,14 +393,14 @@ export class VideoPlayer extends Component { this._impl = VideoPlayerImplManager.getImpl(this); this.syncSource(); - this._impl.componentEventList.set(EventType.META_LOADED, this.onMetaLoaded.bind(this)); - this._impl.componentEventList.set(EventType.READY_TO_PLAY, this.onReadyToPlay.bind(this)); - this._impl.componentEventList.set(EventType.PLAYING, this.onPlaying.bind(this)); - this._impl.componentEventList.set(EventType.PAUSED, this.onPaused.bind(this)); - this._impl.componentEventList.set(EventType.STOPPED, this.onStopped.bind(this)); - this._impl.componentEventList.set(EventType.COMPLETED, this.onCompleted.bind(this)); - this._impl.componentEventList.set(EventType.ERROR, this.onError.bind(this)); - this._impl.componentEventList.set(EventType.CLICKED, this.onClicked.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.META_LOADED, this.onMetaLoaded.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.READY_TO_PLAY, this.onReadyToPlay.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.PLAYING, this.onPlaying.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.PAUSED, this.onPaused.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.STOPPED, this.onStopped.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.COMPLETED, this.onCompleted.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.ERROR, this.onError.bind(this)); + this._impl.componentEventList.set(VideoPlayerEventType.CLICKED, this.onClicked.bind(this)); if (this._playOnAwake && this._impl.loaded) { this.play(); } @@ -432,44 +432,44 @@ export class VideoPlayer extends Component { } public onMetaLoaded (): void { - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.META_LOADED); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.META_LOADED); this.node.emit('meta-loaded', this); } public onReadyToPlay (): void { if (this._playOnAwake && !this.isPlaying) { this.play(); } - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.READY_TO_PLAY); - this.node.emit(EventType.READY_TO_PLAY, this); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.READY_TO_PLAY); + this.node.emit(VideoPlayerEventType.READY_TO_PLAY, this); } public onPlaying (): void { - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PLAYING); - this.node.emit(EventType.PLAYING, this); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.PLAYING); + this.node.emit(VideoPlayerEventType.PLAYING, this); } public onPaused (): void { - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PAUSED); - this.node.emit(EventType.PAUSED, this); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.PAUSED); + this.node.emit(VideoPlayerEventType.PAUSED, this); } public onStopped (): void { - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.STOPPED); - this.node.emit(EventType.STOPPED, this); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.STOPPED); + this.node.emit(VideoPlayerEventType.STOPPED, this); } public onCompleted (): void { - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.COMPLETED); - this.node.emit(EventType.COMPLETED, this); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.COMPLETED); + this.node.emit(VideoPlayerEventType.COMPLETED, this); } public onError (): void { - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.ERROR); - this.node.emit(EventType.ERROR, this); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.ERROR); + this.node.emit(VideoPlayerEventType.ERROR, this); } public onClicked (): void { - ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.CLICKED); - this.node.emit(EventType.CLICKED, this); + ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, VideoPlayerEventType.CLICKED); + this.node.emit(VideoPlayerEventType.CLICKED, this); } /** diff --git a/cocos/web-view/web-view-enums.ts b/cocos/web-view/web-view-enums.ts index dbbc9d159d3..844e92cdcc5 100644 --- a/cocos/web-view/web-view-enums.ts +++ b/cocos/web-view/web-view-enums.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ -export enum EventType { +export enum WebViewEventType { /** * @en None. * @zh 无。 diff --git a/cocos/web-view/web-view-impl-web.ts b/cocos/web-view/web-view-impl-web.ts index a290677d4b8..b77ffde0ed4 100644 --- a/cocos/web-view/web-view-impl-web.ts +++ b/cocos/web-view/web-view-impl-web.ts @@ -23,7 +23,7 @@ */ import { screenAdapter } from 'pal/screen-adapter'; -import { EventType } from './web-view-enums'; +import { WebViewEventType } from './web-view-enums'; import { error, warn } from '../core/platform'; import { WebViewImpl } from './web-view-impl'; import { game } from '../game'; @@ -46,12 +46,12 @@ export class WebViewImplWeb extends WebViewImpl { } const onLoaded = (e: Event): void => { this._forceUpdate = true; - this.dispatchEvent(EventType.LOADED); + this.dispatchEvent(WebViewEventType.LOADED); const iframe = e.target as HTMLIFrameElement; const body = iframe.contentDocument && iframe.contentDocument.body; if (body && body.innerHTML.includes('404')) { - this.dispatchEvent(EventType.ERROR, body.innerHTML); + this.dispatchEvent(WebViewEventType.ERROR, body.innerHTML); } }; @@ -62,7 +62,7 @@ export class WebViewImplWeb extends WebViewImpl { if (this.webview) { this.webview.src = url; // emit loading event - this.dispatchEvent(EventType.LOADING); + this.dispatchEvent(WebViewEventType.LOADING); } } @@ -116,7 +116,7 @@ export class WebViewImplWeb extends WebViewImpl { try { win.eval(str); } catch (e) { - this.dispatchEvent(EventType.ERROR, e); + this.dispatchEvent(WebViewEventType.ERROR, e); error(e); } } diff --git a/cocos/web-view/web-view-impl.ts b/cocos/web-view/web-view-impl.ts index 85828f81347..8cbbabe350b 100644 --- a/cocos/web-view/web-view-impl.ts +++ b/cocos/web-view/web-view-impl.ts @@ -24,15 +24,15 @@ import { legacyCC } from '../core/global-exports'; import { WebView } from './web-view'; -import { EventType } from './web-view-enums'; +import { WebViewEventType } from './web-view-enums'; import { UITransform } from '../2d/framework'; import { director } from '../game/director'; import { Node } from '../scene-graph'; import type { Camera } from '../render-scene/scene'; export abstract class WebViewImpl { - protected _componentEventList: Map void> = new Map(); - protected _state = EventType.NONE; + protected _componentEventList: Map void> = new Map(); + protected _state = WebViewEventType.NONE; protected _wrapper: any; // Fix iframe display problem in ios. protected _webview: HTMLIFrameElement | null = null; @@ -72,7 +72,7 @@ export abstract class WebViewImpl { this._m05 = 0; this._m12 = 0; this._m13 = 0; - this._state = EventType.NONE; + this._state = WebViewEventType.NONE; this._forceUpdate = false; } @@ -88,14 +88,14 @@ export abstract class WebViewImpl { public abstract setJavascriptInterfaceScheme(scheme: string): void; get loaded (): boolean { return this._loaded; } - get componentEventList (): Map void> { return this._componentEventList; } + get componentEventList (): Map void> { return this._componentEventList; } get webview (): HTMLIFrameElement | null { return this._webview; } - get state (): EventType { return this._state; } + get state (): WebViewEventType { return this._state; } get UICamera (): Camera | null { return director.root!.batcher2D.getFirstRenderCamera(this._node!); } - protected dispatchEvent (key: EventType, ...args: any[any]): void { + protected dispatchEvent (key: WebViewEventType, ...args: any[any]): void { const callback = this._componentEventList.get(key); if (callback) { this._state = key; diff --git a/cocos/web-view/web-view.ts b/cocos/web-view/web-view.ts index 68f7d978fc5..1e9835c72ae 100644 --- a/cocos/web-view/web-view.ts +++ b/cocos/web-view/web-view.ts @@ -27,7 +27,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { UITransform } from '../2d/framework'; import { Component, EventHandler as ComponentEventHandler } from '../scene-graph'; import { WebViewImplManager } from './web-view-impl-manager'; -import { EventType } from './web-view-enums'; +import { WebViewEventType } from './web-view-enums'; import { legacyCC } from '../core/global-exports'; import type { WebViewImpl } from './web-view-impl'; @@ -55,7 +55,7 @@ export class WebView extends Component { * @en WebView event type. * @zh 网页视图事件类型。 */ - public static EventType = EventType; + public static EventType = WebViewEventType; /** * @en @@ -102,8 +102,8 @@ export class WebView extends Component { * @zh * 获取当前网页视图状态。 */ - get state (): EventType { - if (!this._impl) { return EventType.NONE; } + get state (): WebViewEventType { + if (!this._impl) { return WebViewEventType.NONE; } return this._impl.state; } @@ -167,25 +167,25 @@ export class WebView extends Component { } this._impl = WebViewImplManager.getImpl(this); // must be register the event listener - this._impl.componentEventList.set(EventType.LOADING, this.onLoading.bind(this)); - this._impl.componentEventList.set(EventType.LOADED, this.onLoaded.bind(this)); - this._impl.componentEventList.set(EventType.ERROR, this.onError.bind(this)); + this._impl.componentEventList.set(WebViewEventType.LOADING, this.onLoading.bind(this)); + this._impl.componentEventList.set(WebViewEventType.LOADED, this.onLoaded.bind(this)); + this._impl.componentEventList.set(WebViewEventType.ERROR, this.onError.bind(this)); this._impl.loadURL(this._url); } onLoading (): void { - ComponentEventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING); - this.node.emit(EventType.LOADING, this); + ComponentEventHandler.emitEvents(this.webviewEvents, this, WebViewEventType.LOADING); + this.node.emit(WebViewEventType.LOADING, this); } onLoaded (): void { - ComponentEventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED); - this.node.emit(EventType.LOADED, this); + ComponentEventHandler.emitEvents(this.webviewEvents, this, WebViewEventType.LOADED); + this.node.emit(WebViewEventType.LOADED, this); } onError (...args: any[any]): void { - ComponentEventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR, args); - this.node.emit(EventType.ERROR, this, args); + ComponentEventHandler.emitEvents(this.webviewEvents, this, WebViewEventType.ERROR, args); + this.node.emit(WebViewEventType.ERROR, this, args); } public onEnable (): void { diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 43cd5ade696..a28d6a98a0f 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -953,6 +953,10 @@ struct Viewport { float maxDepth{1.F}; EXPOSE_COPY_FN(Viewport) + + void reset() { + *this = Viewport(); + } }; struct Color { @@ -1335,8 +1339,8 @@ struct ALIGNAS(8) SubpassDependency { uint32_t dstSubpass{0}; GeneralBarrier *generalBarrier{nullptr}; - AccessFlags prevAccesses{}; - AccessFlags nextAccesses{}; + AccessFlags prevAccesses{AccessFlagBit::NONE}; + AccessFlags nextAccesses{AccessFlagBit::NONE}; EXPOSE_COPY_FN(SubpassDependency) }; diff --git a/native/tools/gfx-define-generator/generate.js b/native/tools/gfx-define-generator/generate.js index be60899f861..c60a0793b2a 100644 --- a/native/tools/gfx-define-generator/generate.js +++ b/native/tools/gfx-define-generator/generate.js @@ -142,6 +142,7 @@ const replaceConstants = (() => { const strMap = { nullptr: 'null!', '::': '.', + 'INVALID_SHADER_HASH': '0xFFFFFFFF' }; const constexprRE = /constexpr\s+\w+\s+(\w+)\s*=\s*(.*);/g; let constexprCap = constexprRE.exec(header); @@ -185,6 +186,7 @@ while (structCap) { type = type.replace(/(\b)(?:bool)(\b)/, '$1boolean$2'); type = type.replace(/(\b)(?:String)(\b)/, '$1string$2'); type = type.replace(/(\b)(?:ccstd::string)(\b)/, '$1string$2'); + type = type.replace(/(\b)(?:ccstd::hash_t)(\b)/, '$1number$2'); if (memberCap[1]) {readonly = true;} const isArray = type.endsWith('[]'); const decayedType = isArray ? type.slice(0, -2) : type; @@ -286,7 +288,7 @@ for (const name of Object.keys(structMap)) { output += ` ) {}\n`; if (!Object.keys(struct.member).some((k) => struct.member[k].readonly)) { - output += `\n public copy (info: Readonly<${name}>) {\n`; + output += `\n public copy (info: Readonly<${name}>): ${name} {\n`; for (const key in struct.member) { const {decayedType, isArray} = struct.member[key]; if (isArray) { diff --git a/native/tools/gfx-define-generator/package-lock.json b/native/tools/gfx-define-generator/package-lock.json index 4dc83b33ae1..ea7f439a759 100644 --- a/native/tools/gfx-define-generator/package-lock.json +++ b/native/tools/gfx-define-generator/package-lock.json @@ -1,20 +1,31 @@ { "name": "gfx-define-generator", "version": "1.0.0", - "lockfileVersion": 1, + "lockfileVersion": 3, "requires": true, - "dependencies": { - "argparse": { + "packages": { + "": { + "name": "gfx-define-generator", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "js-yaml": "^4.0.0" + } + }, + "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" }, - "js-yaml": { + "node_modules/js-yaml": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.0.0.tgz", "integrity": "sha512-pqon0s+4ScYUvX30wxQi3PogGFAlUyH0awepWvwkj4jD4v+ova3RiYw8bmA6x2rDrEaj8i/oWKoRxpVNW+Re8Q==", - "requires": { + "dependencies": { "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" } } } diff --git a/package-lock.json b/package-lock.json index eedd61f4453..4d7273c376a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@babel/plugin-proposal-class-properties": "^7.18.6", "@cocos/box2d": "1.0.1", "@cocos/cannon": "1.2.8", - "@cocos/ccbuild": "2.2.11", + "@cocos/ccbuild": "^2.2.15", "@cocos/dragonbones-js": "^1.0.1" }, "devDependencies": { @@ -481,17 +481,17 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", - "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.8.tgz", + "integrity": "sha512-pO9KhhRcuUyGnJWwyEgnRJTSIZHiT+vMD0kPeD+so0l7mxkMT19g3pjY9GTnHySck/hDzq+dtW/4VgnMkippsQ==", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", + "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", "engines": { "node": ">=6.9.0" } @@ -623,9 +623,12 @@ } }, "node_modules/@babel/parser": { - "version": "7.22.16", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.22.16.tgz", - "integrity": "sha512-+gPfKv8UWeKKeJTUxe59+OobVcrYHETCsORl61EmSkmgymguYk/X5bp7GuUIXaFsc6y++v8ZxPsLSSuujqDphA==", + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.6.tgz", + "integrity": "sha512-trGdfBdbD0l1ZPmcJ83eNxB9rbEax4ALFTF7fN386TMYbeCQbyme5cOEXQhbGXKebwGaB/J52w1mrklMcbgy6Q==", + "dependencies": { + "@babel/types": "^7.25.6" + }, "bin": { "parser": "bin/babel-parser.js" }, @@ -1991,12 +1994,12 @@ } }, "node_modules/@babel/types": { - "version": "7.22.19", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.22.19.tgz", - "integrity": "sha512-P7LAw/LbojPzkgp5oznjE6tQEIWbp4PkkfrZDINTro9zgBRtI324/EYsiSI7lhPbpIQ+DCeR2NNmMWANGGfZsg==", + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.6.tgz", + "integrity": "sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==", "dependencies": { - "@babel/helper-string-parser": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.19", + "@babel/helper-string-parser": "^7.24.8", + "@babel/helper-validator-identifier": "^7.24.7", "to-fast-properties": "^2.0.0" }, "engines": { @@ -2056,9 +2059,9 @@ } }, "node_modules/@cocos/ccbuild": { - "version": "2.2.11", - "resolved": "https://registry.npmjs.org/@cocos/ccbuild/-/ccbuild-2.2.11.tgz", - "integrity": "sha512-pjLTvfhA4vOt8k1pn6velsurCdnakUn1QB/zOJoIPleI6yhEfDIpoQ8dXX0nkE6e2cU52DYmuYH795iTGfdQiQ==", + "version": "2.2.15", + "resolved": "https://registry.npmjs.org/@cocos/ccbuild/-/ccbuild-2.2.15.tgz", + "integrity": "sha512-P4vBIghbF2nBjD+XwgYCLA7AFHDrk0ZYEJVaBQaB5zqpvXDqFsJc0PnMk2Q//5xVk0Aajhu6Lnwfls6xtY+9YA==", "dependencies": { "@babel/core": "^7.20.12", "@babel/helper-module-imports": "7.18.6", @@ -2073,11 +2076,14 @@ "@cocos/creator-programming-babel-preset-cc": "1.0.1-alpha.5", "@cocos/tfig": "3.3.3", "@rollup/plugin-babel": "^6.0.3", - "@rollup/plugin-commonjs": "^11.1.0", - "@rollup/plugin-json": "^4.1.0", - "@rollup/plugin-node-resolve": "^7.1.3", - "@rollup/plugin-typescript": "~11.1.2", - "@rollup/plugin-virtual": "^3.0.1", + "@rollup/plugin-commonjs": "^26.0.1", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "5.0.7", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "~11.1.6", + "@rollup/plugin-virtual": "^3.0.2", + "@rollup/pluginutils": "5.1.0", "@types/babel__core": "7.1.20", "@types/babel__generator": "7.6.4", "@types/babel__helper-module-imports": "7.18.0", @@ -2085,16 +2091,18 @@ "@types/babel__template": "7.4.1", "@types/babel__traverse": "7.18.2", "@types/resolve": "^1.20.2", + "ast-kit": "1.0.0", "commander": "~11.0.0", "dedent": "^0.7.0", "ejs": "~3.1.9", + "fast-glob": "3.3.2", "fs-extra": "~11.1.1", "glob": "~7.2.0", "json5": "^2.2.3", + "magic-string": "^0.30.10", "path": "~0.12.7", "resolve": "^1.22.1", - "rollup": "^2.79.1", - "rollup-plugin-terser": "^7.0.2", + "rollup": "^4.20.0", "semver": "~7.5.3", "typescript": "^4.9.5" }, @@ -2320,61 +2328,65 @@ "node": ">=6.0.0" } }, - "node_modules/@cocos/ccbuild/node_modules/@rollup/plugin-babel": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-6.0.3.tgz", - "integrity": "sha512-fKImZKppa1A/gX73eg4JGo+8kQr/q1HBQaCGKECZ0v4YBBv3lFqi14+7xyApECzvkLTHCifx+7ntcrvtBIRcpg==", + "node_modules/@cocos/ccbuild/node_modules/@rollup/plugin-commonjs": { + "version": "26.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-26.0.3.tgz", + "integrity": "sha512-2BJcolt43MY+y5Tz47djHkodCC3c1VKVrBDKpVqHKpQ9z9S158kCCqB8NF6/gzxLdNlYW9abB3Ibh+kOWLp8KQ==", "dependencies": { - "@babel/helper-module-imports": "^7.18.6", - "@rollup/pluginutils": "^5.0.1" + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "glob": "^10.4.1", + "is-reference": "1.2.1", + "magic-string": "^0.30.3" }, "engines": { - "node": ">=14.0.0" + "node": ">=16.0.0 || 14 >= 14.17" }, "peerDependencies": { - "@babel/core": "^7.0.0", - "@types/babel__core": "^7.1.9", - "rollup": "^1.20.0||^2.0.0||^3.0.0" + "rollup": "^2.68.0||^3.0.0||^4.0.0" }, "peerDependenciesMeta": { - "@types/babel__core": { - "optional": true - }, "rollup": { "optional": true } } }, - "node_modules/@cocos/ccbuild/node_modules/@rollup/plugin-virtual": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@rollup/plugin-virtual/-/plugin-virtual-3.0.1.tgz", - "integrity": "sha512-fK8O0IL5+q+GrsMLuACVNk2x21g3yaw+sG2qn16SnUd3IlBsQyvWxLMGHmCmXRMecPjGRSZ/1LmZB4rjQm68og==", - "engines": { - "node": ">=14.0.0" + "node_modules/@cocos/ccbuild/node_modules/@rollup/plugin-commonjs/node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" }, - "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0" + "bin": { + "glob": "dist/esm/bin.mjs" }, - "peerDependenciesMeta": { - "rollup": { - "optional": true - } + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@cocos/ccbuild/node_modules/@rollup/pluginutils": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.0.2.tgz", - "integrity": "sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==", + "node_modules/@cocos/ccbuild/node_modules/@rollup/plugin-node-resolve": { + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.3.0.tgz", + "integrity": "sha512-9eO5McEICxMzJpDW9OnMYSv4Sta3hmt7VtBFz5zR9273suNOydOyq/FrGeGy+KsTRFm8w0SLVhzig2ILFT63Ag==", "dependencies": { - "@types/estree": "^1.0.0", - "estree-walker": "^2.0.2", - "picomatch": "^2.3.1" + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" }, "engines": { "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0" + "rollup": "^2.78.0||^3.0.0||^4.0.0" }, "peerDependenciesMeta": { "rollup": { @@ -2383,15 +2395,23 @@ } }, "node_modules/@cocos/ccbuild/node_modules/@types/estree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.1.tgz", - "integrity": "sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==" + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", + "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==" }, "node_modules/@cocos/ccbuild/node_modules/@types/resolve": { "version": "1.20.2", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==" }, + "node_modules/@cocos/ccbuild/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, "node_modules/@cocos/ccbuild/node_modules/commander": { "version": "11.0.0", "resolved": "https://registry.npmjs.org/commander/-/commander-11.0.0.tgz", @@ -2400,11 +2420,6 @@ "node": ">=16" } }, - "node_modules/@cocos/ccbuild/node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" - }, "node_modules/@cocos/ccbuild/node_modules/fs-extra": { "version": "11.1.1", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.1.1.tgz", @@ -2442,17 +2457,51 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/@cocos/ccbuild/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@cocos/ccbuild/node_modules/rollup": { - "version": "2.79.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.1.tgz", - "integrity": "sha512-uKxbd0IhMZOhjAiD5oAFp7BqvkA4Dv47qpOCtaNvng4HBwdbWtdOh8f5nZNuk2rp51PMGk3bzfWu5oayNEuYnw==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.22.4.tgz", + "integrity": "sha512-vD8HJ5raRcWOyymsR6Z3o6+RzfEPCnVLMFJ6vRslO1jt4LO6dUo5Qnpg7y4RkZFM2DMe3WUirkI5c16onjrc6A==", + "dependencies": { + "@types/estree": "1.0.5" + }, "bin": { "rollup": "dist/bin/rollup" }, "engines": { - "node": ">=10.0.0" + "node": ">=18.0.0", + "npm": ">=8.0.0" }, "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.22.4", + "@rollup/rollup-android-arm64": "4.22.4", + "@rollup/rollup-darwin-arm64": "4.22.4", + "@rollup/rollup-darwin-x64": "4.22.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.22.4", + "@rollup/rollup-linux-arm-musleabihf": "4.22.4", + "@rollup/rollup-linux-arm64-gnu": "4.22.4", + "@rollup/rollup-linux-arm64-musl": "4.22.4", + "@rollup/rollup-linux-powerpc64le-gnu": "4.22.4", + "@rollup/rollup-linux-riscv64-gnu": "4.22.4", + "@rollup/rollup-linux-s390x-gnu": "4.22.4", + "@rollup/rollup-linux-x64-gnu": "4.22.4", + "@rollup/rollup-linux-x64-musl": "4.22.4", + "@rollup/rollup-win32-arm64-msvc": "4.22.4", + "@rollup/rollup-win32-ia32-msvc": "4.22.4", + "@rollup/rollup-win32-x64-msvc": "4.22.4", "fsevents": "~2.3.2" } }, @@ -2819,6 +2868,95 @@ "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", "dev": true }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -4032,44 +4170,44 @@ } }, "node_modules/@jridgewell/set-array": { - "version": "1.1.2", - "resolved": "https://registry.npmmirror.com/@jridgewell/set-array/-/set-array-1.1.2.tgz", - "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", "engines": { "node": ">=6.0.0" } }, "node_modules/@jridgewell/source-map": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.3.tgz", - "integrity": "sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg==", + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.6.tgz", + "integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==", "dependencies": { - "@jridgewell/gen-mapping": "^0.3.0", - "@jridgewell/trace-mapping": "^0.3.9" + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" } }, "node_modules/@jridgewell/source-map/node_modules/@jridgewell/gen-mapping": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", - "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", "dependencies": { - "@jridgewell/set-array": "^1.0.1", + "@jridgewell/set-array": "^1.2.1", "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.9" + "@jridgewell/trace-mapping": "^0.3.24" }, "engines": { "node": ">=6.0.0" } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==" }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.19", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", - "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" @@ -4107,116 +4245,113 @@ "node": ">= 8" } }, - "node_modules/@rollup/plugin-commonjs": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.1.0.tgz", - "integrity": "sha512-Ycr12N3ZPN96Fw2STurD21jMqzKwL9QuFhms3SD7KKRK7oaXUsBU9Zt0jL/rOPHiPYisI21/rXGO3jr9BnLHUA==", - "dependencies": { - "@rollup/pluginutils": "^3.0.8", - "commondir": "^1.0.1", - "estree-walker": "^1.0.1", - "glob": "^7.1.2", - "is-reference": "^1.1.2", - "magic-string": "^0.25.2", - "resolve": "^1.11.0" - }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "optional": true, "engines": { - "node": ">= 8.0.0" - }, - "peerDependencies": { - "rollup": "^1.20.0||^2.0.0" + "node": ">=14" } }, - "node_modules/@rollup/plugin-commonjs/node_modules/@rollup/pluginutils": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", - "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "node_modules/@rollup/plugin-babel": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-6.0.4.tgz", + "integrity": "sha512-YF7Y52kFdFT/xVSuVdjkV5ZdX/3YtmX0QulG+x0taQOtJdHYzVU61aSSkAgVJ7NOv6qPkIYiJSgSWWN/DM5sGw==", "dependencies": { - "@types/estree": "0.0.39", - "estree-walker": "^1.0.1", - "picomatch": "^2.2.2" + "@babel/helper-module-imports": "^7.18.6", + "@rollup/pluginutils": "^5.0.1" }, "engines": { - "node": ">= 8.0.0" + "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0" - } - }, - "node_modules/@rollup/plugin-json": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.1.0.tgz", - "integrity": "sha512-yfLbTdNS6amI/2OpmbiBoW12vngr5NW2jCJVZSBEz+H5KfUJZ2M7sDjk0U6GOOdCWFVScShte29o9NezJ53TPw==", - "dependencies": { - "@rollup/pluginutils": "^3.0.8" + "@babel/core": "^7.0.0", + "@types/babel__core": "^7.1.9", + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, - "peerDependencies": { - "rollup": "^1.20.0 || ^2.0.0" + "peerDependenciesMeta": { + "@types/babel__core": { + "optional": true + }, + "rollup": { + "optional": true + } } }, - "node_modules/@rollup/plugin-json/node_modules/@rollup/pluginutils": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", - "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "node_modules/@rollup/plugin-json": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz", + "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==", "dependencies": { - "@types/estree": "0.0.39", - "estree-walker": "^1.0.1", - "picomatch": "^2.2.2" + "@rollup/pluginutils": "^5.1.0" }, "engines": { - "node": ">= 8.0.0" + "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0" + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } } }, - "node_modules/@rollup/plugin-node-resolve": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-7.1.3.tgz", - "integrity": "sha512-RxtSL3XmdTAE2byxekYLnx+98kEUOrPHF/KRVjLH+DEIHy6kjIw7YINQzn+NXiH/NTrQLAwYs0GWB+csWygA9Q==", + "node_modules/@rollup/plugin-replace": { + "version": "5.0.7", + "resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-5.0.7.tgz", + "integrity": "sha512-PqxSfuorkHz/SPpyngLyg5GCEkOcee9M1bkxiVDr41Pd61mqP1PLOoDPbpl44SB2mQGKwV/In74gqQmGITOhEQ==", "dependencies": { - "@rollup/pluginutils": "^3.0.8", - "@types/resolve": "0.0.8", - "builtin-modules": "^3.1.0", - "is-module": "^1.0.0", - "resolve": "^1.14.2" + "@rollup/pluginutils": "^5.0.1", + "magic-string": "^0.30.3" }, "engines": { - "node": ">= 8.0.0" + "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0" + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } } }, - "node_modules/@rollup/plugin-node-resolve/node_modules/@rollup/pluginutils": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", - "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "node_modules/@rollup/plugin-terser": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.4.tgz", + "integrity": "sha512-XHeJC5Bgvs8LfukDwWZp7yeqin6ns8RTl2B9avbejt6tZqsqvVoWI7ZTQrcNsfKEDWBTnTxM8nMDkO2IFFbd0A==", "dependencies": { - "@types/estree": "0.0.39", - "estree-walker": "^1.0.1", - "picomatch": "^2.2.2" + "serialize-javascript": "^6.0.1", + "smob": "^1.0.0", + "terser": "^5.17.4" }, "engines": { - "node": ">= 8.0.0" + "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0" + "rollup": "^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } } }, "node_modules/@rollup/plugin-typescript": { - "version": "11.1.2", - "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-11.1.2.tgz", - "integrity": "sha512-0ghSOCMcA7fl1JM+0gYRf+Q/HWyg+zg7/gDSc+fRLmlJWcW5K1I+CLRzaRhXf4Y3DRyPnnDo4M2ktw+a6JcDEg==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-11.1.6.tgz", + "integrity": "sha512-R92yOmIACgYdJ7dJ97p4K69I8gg6IEHt8M7dUBxN3W6nrO8uUxX5ixl0yU/N3aZTi8WhPuICvOHXQvF6FaykAA==", "dependencies": { - "@rollup/pluginutils": "^5.0.1", + "@rollup/pluginutils": "^5.1.0", "resolve": "^1.22.1" }, "engines": { "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^2.14.0||^3.0.0", + "rollup": "^2.14.0||^3.0.0||^4.0.0", "tslib": "*", "typescript": ">=3.7.0" }, @@ -4229,10 +4364,26 @@ } } }, - "node_modules/@rollup/plugin-typescript/node_modules/@rollup/pluginutils": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.0.2.tgz", - "integrity": "sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==", + "node_modules/@rollup/plugin-virtual": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@rollup/plugin-virtual/-/plugin-virtual-3.0.2.tgz", + "integrity": "sha512-10monEYsBp3scM4/ND4LNH5Rxvh3e/cVeL3jWTgZ2SrQ+BmUoQcopVQvnaMcOnykb1VkxUFuDAN+0FnpTFRy2A==", + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.0.tgz", + "integrity": "sha512-XTIWOPPcpvyKI6L1NHo0lFlCyznUEyPmPY1mc3KpPVDYulHSTvyeLNVW00QTLIAFNhR3kYnJTQHeGqU4M3n09g==", "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", @@ -4242,7 +4393,7 @@ "node": ">=14.0.0" }, "peerDependencies": { - "rollup": "^1.20.0||^2.0.0||^3.0.0" + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "peerDependenciesMeta": { "rollup": { @@ -4250,15 +4401,197 @@ } } }, - "node_modules/@rollup/plugin-typescript/node_modules/@types/estree": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.1.tgz", - "integrity": "sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==" + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.22.4.tgz", + "integrity": "sha512-Fxamp4aEZnfPOcGA8KSNEohV8hX7zVHOemC8jVBoBUHu5zpJK/Eu3uJwt6BMgy9fkvzxDaurgj96F/NiLukF2w==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "android" + ] }, - "node_modules/@rollup/plugin-typescript/node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.22.4.tgz", + "integrity": "sha512-VXoK5UMrgECLYaMuGuVTOx5kcuap1Jm8g/M83RnCHBKOqvPPmROFJGQaZhGccnsFtfXQ3XYa4/jMCJvZnbJBdA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.22.4.tgz", + "integrity": "sha512-xMM9ORBqu81jyMKCDP+SZDhnX2QEVQzTcC6G18KlTQEzWK8r/oNZtKuZaCcHhnsa6fEeOBionoyl5JsAbE/36Q==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.22.4.tgz", + "integrity": "sha512-aJJyYKQwbHuhTUrjWjxEvGnNNBCnmpHDvrb8JFDbeSH3m2XdHcxDd3jthAzvmoI8w/kSjd2y0udT+4okADsZIw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.22.4.tgz", + "integrity": "sha512-j63YtCIRAzbO+gC2L9dWXRh5BFetsv0j0va0Wi9epXDgU/XUi5dJKo4USTttVyK7fGw2nPWK0PbAvyliz50SCQ==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.22.4.tgz", + "integrity": "sha512-dJnWUgwWBX1YBRsuKKMOlXCzh2Wu1mlHzv20TpqEsfdZLb3WoJW2kIEsGwLkroYf24IrPAvOT/ZQ2OYMV6vlrg==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.22.4.tgz", + "integrity": "sha512-AdPRoNi3NKVLolCN/Sp4F4N1d98c4SBnHMKoLuiG6RXgoZ4sllseuGioszumnPGmPM2O7qaAX/IJdeDU8f26Aw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.22.4.tgz", + "integrity": "sha512-Gl0AxBtDg8uoAn5CCqQDMqAx22Wx22pjDOjBdmG0VIWX3qUBHzYmOKh8KXHL4UpogfJ14G4wk16EQogF+v8hmA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.22.4.tgz", + "integrity": "sha512-3aVCK9xfWW1oGQpTsYJJPF6bfpWfhbRnhdlyhak2ZiyFLDaayz0EP5j9V1RVLAAxlmWKTDfS9wyRyY3hvhPoOg==", + "cpu": [ + "ppc64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.22.4.tgz", + "integrity": "sha512-ePYIir6VYnhgv2C5Xe9u+ico4t8sZWXschR6fMgoPUK31yQu7hTEJb7bCqivHECwIClJfKgE7zYsh1qTP3WHUA==", + "cpu": [ + "riscv64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.22.4.tgz", + "integrity": "sha512-GqFJ9wLlbB9daxhVlrTe61vJtEY99/xB3C8e4ULVsVfflcpmR6c8UZXjtkMA6FhNONhj2eA5Tk9uAVw5orEs4Q==", + "cpu": [ + "s390x" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.22.4.tgz", + "integrity": "sha512-87v0ol2sH9GE3cLQLNEy0K/R0pz1nvg76o8M5nhMR0+Q+BBGLnb35P0fVz4CQxHYXaAOhE8HhlkaZfsdUOlHwg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.22.4.tgz", + "integrity": "sha512-UV6FZMUgePDZrFjrNGIWzDo/vABebuXBhJEqrHxrGiU6HikPy0Z3LfdtciIttEUQfuDdCn8fqh7wiFJjCNwO+g==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.22.4.tgz", + "integrity": "sha512-BjI+NVVEGAXjGWYHz/vv0pBqfGoUH0IGZ0cICTn7kB9PyjrATSkX+8WkguNjWoj2qSr1im/+tTGRaY+4/PdcQw==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.22.4.tgz", + "integrity": "sha512-SiWG/1TuUdPvYmzmYnmd3IEifzR61Tragkbx9D3+R8mzQqDBz8v+BvZNDlkiTtI9T15KYZhP0ehn3Dld4n9J5g==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.22.4.tgz", + "integrity": "sha512-j8pPKp53/lq9lMXN57S8cFz0MynJk8OWNuUnXct/9KCpKU7DgU3bYMJhwWmcqC0UU29p8Lr0/7KEVcaM6bf47Q==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] }, "node_modules/@sinclair/typebox": { "version": "0.24.51", @@ -4336,9 +4669,9 @@ } }, "node_modules/@types/estree": { - "version": "0.0.39", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", - "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==" + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==" }, "node_modules/@types/fs-extra": { "version": "5.1.0", @@ -4412,7 +4745,8 @@ "node_modules/@types/node": { "version": "17.0.45", "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", - "integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==" + "integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==", + "dev": true }, "node_modules/@types/parse5": { "version": "6.0.3", @@ -4426,14 +4760,6 @@ "integrity": "sha512-+68kP9yzs4LMp7VNh8gdzMSPZFL44MLGqiHWvttYJe+6qnuVr4Ek9wSBQoveqY/r+LwjCcU29kNVkidwim+kYA==", "dev": true }, - "node_modules/@types/resolve": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz", - "integrity": "sha512-auApPaJf3NPfe18hSoJkp8EbZzer2ISk7o8mCC3M9he/a04+gbMF97NkpD2S8riMGvm4BMRI59/SZQSaLTKpsQ==", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/semver": { "version": "7.3.13", "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.3.13.tgz", @@ -4708,18 +5034,6 @@ } } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, - "dependencies": { - "fill-range": "^7.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/@typescript-eslint/typescript-estree/node_modules/debug": { "version": "4.3.4", "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.4.tgz", @@ -4737,46 +5051,6 @@ } } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/fast-glob": { - "version": "3.3.0", - "resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.0.tgz", - "integrity": "sha512-ChDuvbOypPuNjO8yIDf36x7BlZX1smcUMTTcyoIjycexOxd6DFsKsg21qVBzEmr3G7fUKIRy2/psii+CIUt7FA==", - "dev": true, - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.4" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/@typescript-eslint/typescript-estree/node_modules/globby": { "version": "11.1.0", "resolved": "https://registry.npmmirror.com/globby/-/globby-11.1.0.tgz", @@ -4809,28 +5083,6 @@ "node": ">=0.10.0" } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", - "dev": true, - "dependencies": { - "braces": "^3.0.2", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { "version": "7.5.4", "resolved": "https://registry.npmmirror.com/semver/-/semver-7.5.4.tgz", @@ -4846,18 +5098,6 @@ "node": ">=10" } }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, "node_modules/@typescript-eslint/visitor-keys": { "version": "6.0.0", "resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.0.0.tgz", @@ -5353,6 +5593,18 @@ "node": ">=0.10.0" } }, + "node_modules/ast-kit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/ast-kit/-/ast-kit-1.0.0.tgz", + "integrity": "sha512-Jv5Zs4DhU4QEYPvfVrEmdMuxCRMxsIVNfj4uqsBWyNM5wOaNMIfOwu55jH2DWnmr05iyCxPjbYGND1PNU40CuQ==", + "dependencies": { + "@babel/parser": "^7.24.7", + "pathe": "^1.1.2" + }, + "engines": { + "node": ">=16.14.0" + } + }, "node_modules/async": { "version": "2.6.4", "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", @@ -6092,17 +6344,6 @@ "integrity": "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ==", "dev": true }, - "node_modules/builtin-modules": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.3.0.tgz", - "integrity": "sha512-zhaCDicdLuWN5UbN5IMnFqNMhNfo919sH85y2/ea+5Yg9TsTkeZxpL+JLbp6cgYFS4sRLp3YV4S6yDuqVWHYOw==", - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/builtin-status-codes": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", @@ -6525,7 +6766,7 @@ }, "node_modules/commander": { "version": "2.20.3", - "resolved": "https://registry.npmmirror.com/commander/-/commander-2.20.3.tgz", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" }, "node_modules/commondir": { @@ -6796,7 +7037,6 @@ "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -7082,6 +7322,11 @@ "node": ">=0.10.0" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==" + }, "node_modules/ejs": { "version": "3.1.9", "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.9.tgz", @@ -7137,8 +7382,7 @@ "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "devOptional": true + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "node_modules/end-of-stream": { "version": "1.4.4", @@ -8116,9 +8360,9 @@ } }, "node_modules/estree-walker": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", - "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==" + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" }, "node_modules/esutils": { "version": "2.0.3", @@ -8423,36 +8667,35 @@ "dev": true }, "node_modules/fast-glob": { - "version": "3.2.4", - "resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.2.4.tgz", - "integrity": "sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ==", + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", + "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.0", + "glob-parent": "^5.1.2", "merge2": "^1.3.0", - "micromatch": "^4.0.2", - "picomatch": "^2.2.1" + "micromatch": "^4.0.4" }, "engines": { - "node": ">=8" + "node": ">=8.6.0" } }, "node_modules/fast-glob/node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" } }, "node_modules/fast-glob/node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dependencies": { "to-regex-range": "^5.0.1" }, @@ -8462,27 +8705,27 @@ }, "node_modules/fast-glob/node_modules/is-number": { "version": "7.0.0", - "resolved": "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "engines": { "node": ">=0.12.0" } }, "node_modules/fast-glob/node_modules/micromatch": { - "version": "4.0.2", - "resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.2.tgz", - "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", - "dependencies": { - "braces": "^3.0.1", - "picomatch": "^2.0.5" + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" }, "engines": { - "node": ">=8" + "node": ">=8.6" } }, "node_modules/fast-glob/node_modules/to-regex-range": { "version": "5.0.1", - "resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dependencies": { "is-number": "^7.0.0" @@ -8729,6 +8972,72 @@ "node": ">=0.10.0" } }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/foreground-child/node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/foreground-child/node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/foreground-child/node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/form-data": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", @@ -9112,9 +9421,9 @@ } }, "node_modules/glob-parent": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.0.tgz", - "integrity": "sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dependencies": { "is-glob": "^4.0.1" }, @@ -9122,17 +9431,6 @@ "node": ">= 6" } }, - "node_modules/glob-parent/node_modules/is-glob": { - "version": "4.0.1", - "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.1.tgz", - "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/glob-stream": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/glob-stream/-/glob-stream-6.1.0.tgz", @@ -10218,7 +10516,6 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", - "dev": true, "dependencies": { "is-extglob": "^2.1.1" }, @@ -10609,8 +10906,7 @@ "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" }, "node_modules/isobject": { "version": "3.0.1", @@ -10705,6 +11001,20 @@ "node": ">=8" } }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/jake": { "version": "10.8.7", "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.7.tgz", @@ -13253,19 +13563,6 @@ "node": "^12.13.0 || ^14.15.0 || ^16.10.0 || >=17.0.0" } }, - "node_modules/jest-worker": { - "version": "26.6.2", - "resolved": "https://registry.npmmirror.com/jest-worker/-/jest-worker-26.6.2.tgz", - "integrity": "sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==", - "dependencies": { - "@types/node": "*", - "merge-stream": "^2.0.0", - "supports-color": "^7.0.0" - }, - "engines": { - "node": ">= 10.13.0" - } - }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz", @@ -13847,11 +14144,11 @@ } }, "node_modules/magic-string": { - "version": "0.25.9", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz", - "integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==", + "version": "0.30.11", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.11.tgz", + "integrity": "sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==", "dependencies": { - "sourcemap-codec": "^1.4.8" + "@jridgewell/sourcemap-codec": "^1.5.0" } }, "node_modules/make-dir": { @@ -14032,7 +14329,8 @@ "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmmirror.com/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true }, "node_modules/merge2": { "version": "1.4.1", @@ -14193,6 +14491,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/minizlib": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", @@ -14879,6 +15185,11 @@ "node": ">=6" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz", + "integrity": "sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw==" + }, "node_modules/pako": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", @@ -15059,6 +15370,26 @@ "node": ">=0.10.0" } }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==" + }, "node_modules/path-type": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz", @@ -15073,6 +15404,11 @@ "node": ">=0.10.0" } }, + "node_modules/pathe": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", + "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==" + }, "node_modules/pbkdf2": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.2.tgz", @@ -15900,6 +16236,7 @@ "version": "2.26.6", "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.26.6.tgz", "integrity": "sha512-iSB7eE3k/VNQHnI7ckS++4yIqTamoUCB1xo7MswhJ/fg22oFYR5+xCrUZVviBj97jvc5A31MPbVMw1Wc3jWxmw==", + "optional": true, "peer": true, "bin": { "rollup": "dist/bin/rollup" @@ -15911,21 +16248,6 @@ "fsevents": "~2.1.2" } }, - "node_modules/rollup-plugin-terser": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-7.0.2.tgz", - "integrity": "sha512-w3iIaU4OxcF52UUXiZNsNeuXIMDvFrr+ZXK6bFZ0Q60qyVfq4uLptoS4bbq3paG3x216eQllFZX7zt6TIImguQ==", - "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser", - "dependencies": { - "@babel/code-frame": "^7.10.4", - "jest-worker": "^26.2.1", - "serialize-javascript": "^4.0.0", - "terser": "^5.0.0" - }, - "peerDependencies": { - "rollup": "^2.0.0" - } - }, "node_modules/rollup-plugin-visualizer": { "version": "5.9.2", "resolved": "https://registry.npmjs.org/rollup-plugin-visualizer/-/rollup-plugin-visualizer-5.9.2.tgz", @@ -16198,9 +16520,9 @@ } }, "node_modules/serialize-javascript": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-4.0.0.tgz", - "integrity": "sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", "dependencies": { "randombytes": "^2.1.0" } @@ -16363,6 +16685,11 @@ "node": ">=8" } }, + "node_modules/smob": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.5.0.tgz", + "integrity": "sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==" + }, "node_modules/snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -16519,12 +16846,6 @@ "deprecated": "See https://github.com/lydell/source-map-url#deprecated", "dev": true }, - "node_modules/sourcemap-codec": { - "version": "1.4.8", - "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", - "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", - "deprecated": "Please use @jridgewell/sourcemap-codec instead" - }, "node_modules/sparkles": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sparkles/-/sparkles-1.0.1.tgz", @@ -16883,6 +17204,47 @@ "node": ">=0.10.0" } }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/string-width/node_modules/is-fullwidth-code-point": { "version": "1.0.0", "resolved": "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", @@ -16952,6 +17314,26 @@ "node": ">=0.10.0" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, "node_modules/strip-bom": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz", @@ -17106,12 +17488,12 @@ } }, "node_modules/terser": { - "version": "5.17.3", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.17.3.tgz", - "integrity": "sha512-AudpAZKmZHkG9jueayypz4duuCFJMMNGRMwaPvQKWfxKedh8Z2x3OCoDqIIi1xx5+iwx1u6Au8XQcc9Lke65Yg==", + "version": "5.33.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.33.0.tgz", + "integrity": "sha512-JuPVaB7s1gdFKPKTelwUyRq5Sid2A3Gko2S0PncwdBq7kN9Ti9HPWDQ06MPsEDGsZeVESjKEnyGy68quBk1w6g==", "dependencies": { - "@jridgewell/source-map": "^0.3.2", - "acorn": "^8.5.0", + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, @@ -17123,9 +17505,9 @@ } }, "node_modules/terser/node_modules/acorn": { - "version": "8.8.2", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", - "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", "bin": { "acorn": "bin/acorn" }, @@ -17472,13 +17854,6 @@ "node": ">=4" } }, - "node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "optional": true, - "peer": true - }, "node_modules/tty-browserify": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.1.tgz", @@ -18114,7 +18489,6 @@ "version": "2.0.2", "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "dependencies": { "isexe": "^2.0.0" }, @@ -18299,6 +18673,93 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/wrap-ansi-cjs/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz", diff --git a/package.json b/package.json index 0f1a40cbbec..b4dbe7cc977 100644 --- a/package.json +++ b/package.json @@ -80,7 +80,7 @@ "@babel/plugin-proposal-class-properties": "^7.18.6", "@cocos/box2d": "1.0.1", "@cocos/cannon": "1.2.8", - "@cocos/ccbuild": "2.2.11", + "@cocos/ccbuild": "^2.2.15", "@cocos/dragonbones-js": "^1.0.1" } } diff --git a/pal/audio/minigame/player-minigame.ts b/pal/audio/minigame/player-minigame.ts index bb805d6ee81..1df2310e6db 100644 --- a/pal/audio/minigame/player-minigame.ts +++ b/pal/audio/minigame/player-minigame.ts @@ -32,36 +32,36 @@ import { enqueueOperation, OperationInfo, OperationQueueable } from '../operatio import { OS } from '../../system-info/enum-type'; export class OneShotAudioMinigame { - private _innerAudioContext: InnerAudioContext; - private _onPlayCb?: () => void; + private _innerAudioContext$: InnerAudioContext; + private _onPlayCb$?: () => void; get onPlay (): (() => void) | undefined { - return this._onPlayCb; + return this._onPlayCb$; } set onPlay (cb) { - this._onPlayCb = cb; + this._onPlayCb$ = cb; } - private _onEndCb?: () => void; + private _onEndCb$?: () => void; get onEnd (): (() => void) | undefined { - return this._onEndCb; + return this._onEndCb$; } set onEnd (cb) { - this._onEndCb = cb; + this._onEndCb$ = cb; } private constructor (nativeAudio: InnerAudioContext, volume: number) { - this._innerAudioContext = nativeAudio; + this._innerAudioContext$ = nativeAudio; nativeAudio.volume = volume; nativeAudio.onPlay(() => { - this._onPlayCb?.(); + this._onPlayCb$?.(); }); const endCallback = (): void => { - if (this._innerAudioContext) { + if (this._innerAudioContext$) { // NOTE: Type 'null' is not assignable to type 'InnerAudioContext'. - this._innerAudioContext = null as any; - systemInfo.off('hide', this._onInterruptedBegin, this); - systemInfo.off('show', this._onInterruptedEnd, this); - this._onEndCb?.(); + this._innerAudioContext$ = null as any; + systemInfo.off('hide', this._onInterruptedBegin$, this); + systemInfo.off('show', this._onInterruptedEnd$, this); + this._onEndCb$?.(); /**The destroy interface, in some platform implementations, internally invokes stop, * triggering the onStop callback, consequently leading to an infinite loop. **/ nativeAudio.destroy(); @@ -71,32 +71,32 @@ export class OneShotAudioMinigame { nativeAudio.onStop(endCallback);//OneShotAudio can not be reused. // event - systemInfo.on('hide', this._onInterruptedBegin, this); - systemInfo.on('show', this._onInterruptedEnd, this); + systemInfo.on('hide', this._onInterruptedBegin$, this); + systemInfo.on('show', this._onInterruptedEnd$, this); } - private _onInterruptedBegin (): void { - this._innerAudioContext.pause(); + private _onInterruptedBegin$ (): void { + this._innerAudioContext$.pause(); } - private _onInterruptedEnd (): void { - this._innerAudioContext.play(); + private _onInterruptedEnd$ (): void { + this._innerAudioContext$.play(); } public play (): void { - this._innerAudioContext.play(); + this._innerAudioContext$.play(); } public stop (): void { - this._innerAudioContext.stop(); + this._innerAudioContext$.stop(); } } export class AudioPlayerMinigame implements OperationQueueable { - private _innerAudioContext: InnerAudioContext; - private _state: AudioState = AudioState.INIT; - private _cacheTime = 0; - private _needSeek = false; - private _seeking = false; + private _innerAudioContext$: InnerAudioContext; + private _state$: AudioState = AudioState.INIT; + private _cacheTime$ = 0; + private _needSeek$ = false; + private _seeking$ = false; private _onPlay: () => void; private _onPause: () => void; @@ -106,11 +106,11 @@ export class AudioPlayerMinigame implements OperationQueueable { private _readyToHandleOnShow = false; private _resetSeekCache (): void { - this._cacheTime = 0; - this._needSeek = false; - this._seeking = false; - if ((HUAWEI || VIVO || OPPO) && this._innerAudioContext) { - this._innerAudioContext.startTime = 0; + this._cacheTime$ = 0; + this._needSeek$ = false; + this._seeking$ = false; + if ((HUAWEI || VIVO || OPPO) && this._innerAudioContext$) { + this._innerAudioContext$.startTime = 0; } } /** @@ -123,28 +123,28 @@ export class AudioPlayerMinigame implements OperationQueueable { public _operationQueue: OperationInfo[] = []; constructor (innerAudioContext: InnerAudioContext) { - this._innerAudioContext = innerAudioContext; + this._innerAudioContext$ = innerAudioContext; this._eventTarget = new EventTarget(); // event - systemInfo.on('hide', this._onInterruptedBegin, this); - systemInfo.on('show', this._onInterruptedEnd, this); + systemInfo.on('hide', this._onInterruptedBegin$, this); + systemInfo.on('show', this._onInterruptedEnd$, this); const eventTarget = this._eventTarget; this._onPlay = (): void => { - this._state = AudioState.PLAYING; + this._state$ = AudioState.PLAYING; eventTarget.emit(AudioEvent.PLAYED); - if (this._needSeek) { + if (this._needSeek$) { // eslint-disable-next-line @typescript-eslint/no-empty-function - this.seek(this._cacheTime).catch((e) => {}); + this.seek(this._cacheTime$).catch((e) => {}); } }; innerAudioContext.onPlay(this._onPlay); this._onPause = (): void => { - this._state = AudioState.PAUSED; + this._state$ = AudioState.PAUSED; try { - const currentTime = this._innerAudioContext.currentTime; + const currentTime = this._innerAudioContext$.currentTime; if (currentTime !== null && currentTime !== undefined) { - this._cacheTime = currentTime; + this._cacheTime$ = currentTime; } } catch { // Do nothing, cacheTime is not updated. @@ -153,7 +153,7 @@ export class AudioPlayerMinigame implements OperationQueueable { }; innerAudioContext.onPause(this._onPause); this._onStop = (): void => { - this._state = AudioState.STOPPED; + this._state$ = AudioState.STOPPED; // Reset all properties this._resetSeekCache(); eventTarget.emit(AudioEvent.STOPPED); @@ -161,66 +161,66 @@ export class AudioPlayerMinigame implements OperationQueueable { /**Unable to seek again after stop; After stop, regardless of whether the starttime has been set, the playback will always start from 0 again**/ } else { - const currentTime = this._innerAudioContext ? this._innerAudioContext.currentTime : 0; + const currentTime = this._innerAudioContext$ ? this._innerAudioContext$.currentTime : 0; if (currentTime !== 0) { - this._innerAudioContext.seek(0); + this._innerAudioContext$.seek(0); } } }; innerAudioContext.onStop(this._onStop); this._onSeeked = (): void => { eventTarget.emit(AudioEvent.SEEKED); - this._seeking = false; - if (this._needSeek) { - this._needSeek = false; - if (this._cacheTime.toFixed(2) !== this._innerAudioContext.currentTime.toFixed(2)) { + this._seeking$ = false; + if (this._needSeek$) { + this._needSeek$ = false; + if (this._cacheTime$.toFixed(2) !== this._innerAudioContext$.currentTime.toFixed(2)) { // eslint-disable-next-line @typescript-eslint/no-empty-function - this.seek(this._cacheTime).catch((e) => {}); + this.seek(this._cacheTime$).catch((e) => {}); } } }; innerAudioContext.onSeeked(this._onSeeked); this._onEnded = (): void => { - this._state = AudioState.INIT; + this._state$ = AudioState.INIT; this._resetSeekCache(); eventTarget.emit(AudioEvent.ENDED); }; innerAudioContext.onEnded(this._onEnded); } destroy (): void { - systemInfo.off('hide', this._onInterruptedBegin, this); - systemInfo.off('show', this._onInterruptedEnd, this); - if (this._innerAudioContext) { + systemInfo.off('hide', this._onInterruptedBegin$, this); + systemInfo.off('show', this._onInterruptedEnd$, this); + if (this._innerAudioContext$) { ['Play', 'Pause', 'Stop', 'Seeked', 'Ended'].forEach((event) => { - this._offEvent(event); + this._offEvent$(event); }); // NOTE: innerAudioContext might not stop the audio playing, have to call it explicitly. - this._innerAudioContext.stop(); - this._innerAudioContext.destroy(); + this._innerAudioContext$.stop(); + this._innerAudioContext$.destroy(); // NOTE: Type 'null' is not assignable to type 'InnerAudioContext' - this._innerAudioContext = null as any; + this._innerAudioContext$ = null as any; // Restore the state of the audio, otherwise it will cause 'destroy' to be called first and 'stop' to be called later. // this will cause a error. - this._state = AudioState.INIT; + this._state$ = AudioState.INIT; } } - private _onInterruptedBegin (): void { - if (this._state === AudioState.PLAYING) { + private _onInterruptedBegin$ (): void { + if (this._state$ === AudioState.PLAYING) { this.pause().then(() => { - this._state = AudioState.INTERRUPTED; + this._state$ = AudioState.INTERRUPTED; this._readyToHandleOnShow = true; this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN); // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch((e) => {}); } } - private _onInterruptedEnd (): void { + private _onInterruptedEnd$ (): void { // We don't know whether onShow or resolve callback in pause promise is called at first. if (!this._readyToHandleOnShow) { - this._eventTarget.once(AudioEvent.INTERRUPTION_END, this._onInterruptedEnd, this); + this._eventTarget.once(AudioEvent.INTERRUPTION_END, this._onInterruptedEnd$, this); return; } - if (this._state === AudioState.INTERRUPTED) { + if (this._state$ === AudioState.INTERRUPTED) { this.play().then(() => { this._eventTarget.emit(AudioEvent.INTERRUPTION_END); // eslint-disable-next-line @typescript-eslint/no-empty-function @@ -228,15 +228,15 @@ export class AudioPlayerMinigame implements OperationQueueable { } this._readyToHandleOnShow = false; } - private _offEvent (eventName: string): void { + private _offEvent$ (eventName: string): void { if (this[`_on${eventName}`]) { - this._innerAudioContext[`off${eventName}`](this[`_on${eventName}`]); + this._innerAudioContext$[`off${eventName}`](this[`_on${eventName}`]); this[`_on${eventName}`] = null; } } get src (): string { - return this._innerAudioContext ? this._innerAudioContext.src : ''; + return this._innerAudioContext$ ? this._innerAudioContext$.src : ''; } get type (): AudioType { return AudioType.MINIGAME_AUDIO; @@ -288,34 +288,34 @@ export class AudioPlayerMinigame implements OperationQueueable { } get state (): AudioState { - return this._state; + return this._state$; } get loop (): boolean { - return this._innerAudioContext.loop; + return this._innerAudioContext$.loop; } set loop (val: boolean) { - this._innerAudioContext.loop = val; + this._innerAudioContext$.loop = val; } get volume (): number { - return this._innerAudioContext.volume; + return this._innerAudioContext$.volume; } set volume (val: number) { val = clamp01(val); - this._innerAudioContext.volume = val; + this._innerAudioContext$.volume = val; } get duration (): number { // KNOWN ISSUES: duration doesn't work well // On WeChat platform, duration is 0 at the time audio is loaded. - return this._innerAudioContext.duration; + return this._innerAudioContext$.duration; } get currentTime (): number { - if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) { - return this._innerAudioContext.startTime; + if ((HUAWEI || VIVO || OPPO) && (this._state$ === AudioState.STOPPED || this._state$ === AudioState.INIT)) { + return this._innerAudioContext$.startTime; } - if (this._state !== AudioState.PLAYING || this._needSeek || this._seeking) { - return this._cacheTime; + if (this._state$ !== AudioState.PLAYING || this._needSeek$ || this._seeking$) { + return this._cacheTime$; } - return this._innerAudioContext.currentTime; + return this._innerAudioContext$.currentTime; } get sampleRate (): number { @@ -330,19 +330,19 @@ export class AudioPlayerMinigame implements OperationQueueable { seek (time: number): Promise { return new Promise((resolve) => { // KNOWN ISSUES: on Baidu: currentTime returns without numbers on decimal places - if (this._state === AudioState.PLAYING && !this._seeking) { + if (this._state$ === AudioState.PLAYING && !this._seeking$) { time = clamp(time, 0, this.duration); - this._seeking = true; - this._cacheTime = time; + this._seeking$ = true; + this._cacheTime$ = time; this._eventTarget.once(AudioEvent.SEEKED, resolve); - this._innerAudioContext.seek(time); + this._innerAudioContext$.seek(time); } else { //Huawei, vivo, Oppo platform, after stop, regardless of whether the seek has been called, the playback will always start from 0 again - if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) { - this._innerAudioContext.startTime = time; - } else if (this._cacheTime !== time) { // Skip the invalid seek - this._cacheTime = time; - this._needSeek = true; + if ((HUAWEI || VIVO || OPPO) && (this._state$ === AudioState.STOPPED || this._state$ === AudioState.INIT)) { + this._innerAudioContext$.startTime = time; + } else if (this._cacheTime$ !== time) { // Skip the invalid seek + this._cacheTime$ = time; + this._needSeek$ = true; } resolve(); } @@ -353,7 +353,7 @@ export class AudioPlayerMinigame implements OperationQueueable { play (): Promise { return new Promise((resolve) => { this._eventTarget.once(AudioEvent.PLAYED, resolve); - this._innerAudioContext.play(); + this._innerAudioContext$.play(); }); } @@ -364,7 +364,7 @@ export class AudioPlayerMinigame implements OperationQueueable { resolve(); } else { this._eventTarget.once(AudioEvent.PAUSED, resolve); - this._innerAudioContext.pause(); + this._innerAudioContext$.pause(); } }); } @@ -372,13 +372,13 @@ export class AudioPlayerMinigame implements OperationQueueable { @enqueueOperation stop (): Promise { return new Promise((resolve) => { - if (AudioState.INIT === this._state) { + if (AudioState.INIT === this._state$) { this._resetSeekCache(); resolve(); return; } this._eventTarget.once(AudioEvent.STOPPED, resolve); - this._innerAudioContext.stop(); + this._innerAudioContext$.stop(); }); } diff --git a/pal/input/minigame/accelerometer-input.ts b/pal/input/minigame/accelerometer-input.ts index d278ff7933f..59be6b4bc39 100644 --- a/pal/input/minigame/accelerometer-input.ts +++ b/pal/input/minigame/accelerometer-input.ts @@ -30,66 +30,66 @@ import { InputEventType } from '../../../cocos/input/types/event-enum'; import { errorID } from '../../../cocos/core/platform/debug'; export class AccelerometerInputSource { - private _isStarted = false; - private _accelMode: AccelerometerIntervalMode = 'normal'; - private _eventTarget: EventTarget = new EventTarget(); - private declare _didAccelerateFunc: (event: AccelerometerData) => void; + private _isStarted$ = false; + private _accelMode$: AccelerometerIntervalMode = 'normal'; + private _eventTarget$: EventTarget = new EventTarget(); + private declare _didAccelerateFunc$: (event: AccelerometerData) => void; constructor () { - this._didAccelerateFunc = this._didAccelerate.bind(this); + this._didAccelerateFunc$ = this._didAccelerate$.bind(this); } - private _registerEvent (): void { - minigame.onAccelerometerChange(this._didAccelerateFunc); + private _registerEvent$ (): void { + minigame.onAccelerometerChange(this._didAccelerateFunc$); } - private _unregisterEvent (): void { - minigame.offAccelerometerChange(this._didAccelerateFunc); + private _unregisterEvent$ (): void { + minigame.offAccelerometerChange(this._didAccelerateFunc$); } - private _didAccelerate (event: AccelerometerData): void { + private _didAccelerate$ (event: AccelerometerData): void { const timestamp = performance.now(); const acceleration = new Acceleration(event.x, event.y, event.z, timestamp); const eventAcceleration = new EventAcceleration(acceleration); - this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration); + this._eventTarget$.emit(InputEventType.DEVICEMOTION, eventAcceleration); } public start (): void { - this._registerEvent(); + this._registerEvent$(); minigame.startAccelerometer({ - interval: this._accelMode, + interval: this._accelMode$, success: () => { - this._isStarted = true; + this._isStarted$ = true; }, }); } public stop (): void { minigame.stopAccelerometer({ success: () => { - this._isStarted = false; + this._isStarted$ = false; }, fail () { errorID(16305); }, }); - this._unregisterEvent(); + this._unregisterEvent$(); } public setInterval (intervalInMileseconds: number): void { // reference: https://developers.weixin.qq.com/minigame/dev/api/device/accelerometer/wx.startAccelerometer.html if (intervalInMileseconds >= 200) { - this._accelMode = 'normal'; + this._accelMode$ = 'normal'; } else if (intervalInMileseconds >= 60) { - this._accelMode = 'ui'; + this._accelMode$ = 'ui'; } else { - this._accelMode = 'game'; + this._accelMode$ = 'game'; } - if (this._isStarted) { + if (this._isStarted$) { // restart accelerometer this.stop(); this.start(); } } public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); + this._eventTarget$.on(eventType, callback, target); } } diff --git a/pal/input/minigame/gamepad-input.ts b/pal/input/minigame/gamepad-input.ts index 97ff9e90987..c79f92fc916 100644 --- a/pal/input/minigame/gamepad-input.ts +++ b/pal/input/minigame/gamepad-input.ts @@ -32,34 +32,34 @@ export class GamepadInputDevice { public static all: GamepadInputDevice[] = []; public static xr: (GamepadInputDevice | null) = null; - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonL1 (): InputSourceButton { return this._buttonL1; } - public get buttonL2 (): InputSourceButton { return this._buttonL2; } - public get buttonL3 (): InputSourceButton { return this._buttonL3; } - public get buttonR1 (): InputSourceButton { return this._buttonR1; } - public get buttonR2 (): InputSourceButton { return this._buttonR2; } - public get buttonR3 (): InputSourceButton { return this._buttonR3; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth$; } + public get buttonEast (): InputSourceButton { return this._buttonEast$; } + public get buttonWest (): InputSourceButton { return this._buttonWest$; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth$; } + public get buttonL1 (): InputSourceButton { return this._buttonL1$; } + public get buttonL2 (): InputSourceButton { return this._buttonL2$; } + public get buttonL3 (): InputSourceButton { return this._buttonL3$; } + public get buttonR1 (): InputSourceButton { return this._buttonR1$; } + public get buttonR2 (): InputSourceButton { return this._buttonR2$; } + public get buttonR3 (): InputSourceButton { return this._buttonR3$; } // public get buttonTouchPad () { return this._buttonTouchPad; } // public get buttonHome () { return this._buttonHome; } - public get buttonShare (): InputSourceButton { return this._buttonShare; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get dpad (): InputSourceDpad { return this._dpad; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } + public get buttonShare (): InputSourceButton { return this._buttonShare$; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions$; } + public get dpad (): InputSourceDpad { return this._dpad$; } + public get leftStick (): InputSourceStick { return this._leftStick$; } + public get rightStick (): InputSourceStick { return this._rightStick$; } + public get buttonStart (): InputSourceButton { return this._buttonStart$; } + public get gripLeft (): InputSourceButton { return this._gripLeft$; } + public get gripRight (): InputSourceButton { return this._gripRight$; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition$; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation$; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition$; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation$; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition$; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation$; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition$; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation$; } public get deviceId (): number { return this._deviceId; @@ -68,43 +68,43 @@ export class GamepadInputDevice { return this._connected; } - private static _eventTarget: EventTarget = new EventTarget(); - - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonL1: InputSourceButton; - private declare _buttonL2: InputSourceButton; - private declare _buttonL3: InputSourceButton; - private declare _buttonR1: InputSourceButton; - private declare _buttonR2: InputSourceButton; - private declare _buttonR3: InputSourceButton; - // private declare buttonTouchPad: InputSourceButton; - // private declare buttonHome: InputSourceButton; - private declare _buttonShare: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _dpad: InputSourceDpad; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonStart: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; + private static _eventTarget$: EventTarget = new EventTarget(); + + private declare _buttonNorth$: InputSourceButton; + private declare _buttonEast$: InputSourceButton; + private declare _buttonWest$: InputSourceButton; + private declare _buttonSouth$: InputSourceButton; + private declare _buttonL1$: InputSourceButton; + private declare _buttonL2$: InputSourceButton; + private declare _buttonL3$: InputSourceButton; + private declare _buttonR1$: InputSourceButton; + private declare _buttonR2$: InputSourceButton; + private declare _buttonR3$: InputSourceButton; + // private declare buttonTouchPad$: InputSourceButton; + // private declare buttonHome$: InputSourceButton; + private declare _buttonShare$: InputSourceButton; + private declare _buttonOptions$: InputSourceButton; + private declare _dpad$: InputSourceDpad; + private declare _leftStick$: InputSourceStick; + private declare _rightStick$: InputSourceStick; + private declare _buttonStart$: InputSourceButton; + private declare _gripLeft$: InputSourceButton; + private declare _gripRight$: InputSourceButton; + private declare _handLeftPosition$: InputSourcePosition; + private declare _handLeftOrientation$: InputSourceOrientation; + private declare _handRightPosition$: InputSourcePosition; + private declare _handRightOrientation$: InputSourceOrientation; + private declare _aimLeftPosition$: InputSourcePosition; + private declare _aimLeftOrientation$: InputSourceOrientation; + private declare _aimRightPosition$: InputSourcePosition; + private declare _aimRightOrientation$: InputSourceOrientation; private _deviceId = -1; private _connected = false; constructor (deviceId: number) { this._deviceId = deviceId; - this._initInputSource(); + this._initInputSource$(); } /** @@ -118,41 +118,41 @@ export class GamepadInputDevice { * @engineInternal */ public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void { - GamepadInputDevice._eventTarget.on(eventType, cb, target); + GamepadInputDevice._eventTarget$.on(eventType, cb, target); } - private _initInputSource (): void { - this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = (): number => 0; - this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = (): number => 0; - this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = (): number => 0; - this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = (): number => 0; - - this._buttonL1 = new InputSourceButton(); - this._buttonL1.getValue = (): number => 0; - this._buttonL2 = new InputSourceButton(); - this._buttonL2.getValue = (): number => 0; - this._buttonL3 = new InputSourceButton(); - this._buttonL3.getValue = (): number => 0; - this._buttonR1 = new InputSourceButton(); - this._buttonR1.getValue = (): number => 0; - this._buttonR2 = new InputSourceButton(); - this._buttonR2.getValue = (): number => 0; - this._buttonR3 = new InputSourceButton(); - this._buttonR3.getValue = (): number => 0; + private _initInputSource$ (): void { + this._buttonNorth$ = new InputSourceButton(); + this._buttonNorth$.getValue = (): number => 0; + this._buttonEast$ = new InputSourceButton(); + this._buttonEast$.getValue = (): number => 0; + this._buttonWest$ = new InputSourceButton(); + this._buttonWest$.getValue = (): number => 0; + this._buttonSouth$ = new InputSourceButton(); + this._buttonSouth$.getValue = (): number => 0; + + this._buttonL1$ = new InputSourceButton(); + this._buttonL1$.getValue = (): number => 0; + this._buttonL2$ = new InputSourceButton(); + this._buttonL2$.getValue = (): number => 0; + this._buttonL3$ = new InputSourceButton(); + this._buttonL3$.getValue = (): number => 0; + this._buttonR1$ = new InputSourceButton(); + this._buttonR1$.getValue = (): number => 0; + this._buttonR2$ = new InputSourceButton(); + this._buttonR2$.getValue = (): number => 0; + this._buttonR3$ = new InputSourceButton(); + this._buttonR3$.getValue = (): number => 0; // this._buttonTouchPad = new InputSourceButton(); // this._buttonTouchPad.getValue = () => 0; // this._buttonHome = new InputSourceButton(); // this._buttonHome.getValue = () => 0; - this._buttonShare = new InputSourceButton(); - this._buttonShare.getValue = (): number => 0; - this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = (): number => 0; + this._buttonShare$ = new InputSourceButton(); + this._buttonShare$.getValue = (): number => 0; + this._buttonOptions$ = new InputSourceButton(); + this._buttonOptions$.getValue = (): number => 0; const dpadUp = new InputSourceButton(); dpadUp.getValue = (): number => 0; @@ -162,7 +162,7 @@ export class GamepadInputDevice { dpadLeft.getValue = (): number => 0; const dpadRight = new InputSourceButton(); dpadRight.getValue = (): number => 0; - this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); + this._dpad$ = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight }); const leftStickUp = new InputSourceButton(); leftStickUp.getValue = (): number => 0; @@ -172,7 +172,7 @@ export class GamepadInputDevice { leftStickLeft.getValue = (): number => 0; const leftStickRight = new InputSourceButton(); leftStickRight.getValue = (): number => 0; - this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + this._leftStick$ = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); const rightStickUp = new InputSourceButton(); rightStickUp.getValue = (): number => 0; @@ -182,34 +182,34 @@ export class GamepadInputDevice { rightStickLeft.getValue = (): number => 0; const rightStickRight = new InputSourceButton(); rightStickRight.getValue = (): number => 0; - this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); - - this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = (): number => 0; - - this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = (): number => 0; - this._gripRight = new InputSourceButton(); - this._gripRight.getValue = (): number => 0; - - this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; + this._rightStick$ = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._buttonStart$ = new InputSourceButton(); + this._buttonStart$.getValue = (): number => 0; + + this._gripLeft$ = new InputSourceButton(); + this._gripLeft$.getValue = (): number => 0; + this._gripRight$ = new InputSourceButton(); + this._gripRight$.getValue = (): number => 0; + + this._handLeftPosition$ = new InputSourcePosition(); + this._handLeftPosition$.getValue = (): Readonly => Vec3.ZERO; + this._handLeftOrientation$ = new InputSourceOrientation(); + this._handLeftOrientation$.getValue = (): Readonly => Quat.IDENTITY; + + this._handRightPosition$ = new InputSourcePosition(); + this._handRightPosition$.getValue = (): Readonly => Vec3.ZERO; + this._handRightOrientation$ = new InputSourceOrientation(); + this._handRightOrientation$.getValue = (): Readonly => Quat.IDENTITY; + + this._aimLeftPosition$ = new InputSourcePosition(); + this._aimLeftPosition$.getValue = (): Readonly => Vec3.ZERO; + this._aimLeftOrientation$ = new InputSourceOrientation(); + this._aimLeftOrientation$.getValue = (): Readonly => Quat.IDENTITY; + + this._aimRightPosition$ = new InputSourcePosition(); + this._aimRightPosition$.getValue = (): Readonly => Vec3.ZERO; + this._aimRightOrientation$ = new InputSourceOrientation(); + this._aimRightOrientation$.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/minigame/handheld-input.ts b/pal/input/minigame/handheld-input.ts index 4f5b6ba9201..82beab9696d 100644 --- a/pal/input/minigame/handheld-input.ts +++ b/pal/input/minigame/handheld-input.ts @@ -29,13 +29,13 @@ import { InputSourcePosition, InputSourceOrientation } from '../input-source'; import { Quat, Vec3 } from '../../../cocos/core/math'; export class HandheldInputDevice { - public get handheldPosition (): InputSourcePosition { return this._handheldPosition; } - public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; } + public get handheldPosition (): InputSourcePosition { return this._handheldPosition$; } + public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation$; } - private _eventTarget: EventTarget = new EventTarget(); + private _eventTarget$: EventTarget = new EventTarget(); - private declare _handheldPosition: InputSourcePosition; - private declare _handheldOrientation: InputSourceOrientation; + private declare _handheldPosition$: InputSourcePosition; + private declare _handheldOrientation$: InputSourceOrientation; constructor () { this._initInputSource(); @@ -45,13 +45,13 @@ export class HandheldInputDevice { * @engineInternal */ public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); + this._eventTarget$.on(eventType, callback, target); } private _initInputSource (): void { - this._handheldPosition = new InputSourcePosition(); - this._handheldPosition.getValue = (): Readonly => Vec3.ZERO; - this._handheldOrientation = new InputSourceOrientation(); - this._handheldOrientation.getValue = (): Readonly => Quat.IDENTITY; + this._handheldPosition$ = new InputSourcePosition(); + this._handheldPosition$.getValue = (): Readonly => Vec3.ZERO; + this._handheldOrientation$ = new InputSourceOrientation(); + this._handheldOrientation$.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/minigame/handle-input.ts b/pal/input/minigame/handle-input.ts index 8be6a55e045..57a8ad608e6 100644 --- a/pal/input/minigame/handle-input.ts +++ b/pal/input/minigame/handle-input.ts @@ -29,76 +29,76 @@ import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOr import { Vec3, Quat } from '../../../cocos/core/math'; export class HandleInputDevice { - public get buttonNorth (): InputSourceButton { return this._buttonNorth; } - public get buttonEast (): InputSourceButton { return this._buttonEast; } - public get buttonWest (): InputSourceButton { return this._buttonWest; } - public get buttonSouth (): InputSourceButton { return this._buttonSouth; } - public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; } - public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; } - public get triggerLeft (): InputSourceButton { return this._triggerLeft; } - public get triggerRight (): InputSourceButton { return this._triggerRight; } - public get gripLeft (): InputSourceButton { return this._gripLeft; } - public get gripRight (): InputSourceButton { return this._gripRight; } - public get leftStick (): InputSourceStick { return this._leftStick; } - public get rightStick (): InputSourceStick { return this._rightStick; } - public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; } - public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; } - public get buttonOptions (): InputSourceButton { return this._buttonOptions; } - public get buttonStart (): InputSourceButton { return this._buttonStart; } - public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; } - public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; } - public get handRightPosition (): InputSourcePosition { return this._handRightPosition; } - public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; } - public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; } - public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; } - public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; } - public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; } - public get touchButtonA (): InputSourceTouch { return this._touchButtonA; } - public get touchButtonB (): InputSourceTouch { return this._touchButtonB; } - public get touchButtonX (): InputSourceTouch { return this._touchButtonX; } - public get touchButtonY (): InputSourceTouch { return this._touchButtonY; } - public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; } - public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; } - public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; } - public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; } + public get buttonNorth (): InputSourceButton { return this._buttonNorth$; } + public get buttonEast (): InputSourceButton { return this._buttonEast$; } + public get buttonWest (): InputSourceButton { return this._buttonWest$; } + public get buttonSouth (): InputSourceButton { return this._buttonSouth$; } + public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft$; } + public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight$; } + public get triggerLeft (): InputSourceButton { return this._triggerLeft$; } + public get triggerRight (): InputSourceButton { return this._triggerRight$; } + public get gripLeft (): InputSourceButton { return this._gripLeft$; } + public get gripRight (): InputSourceButton { return this._gripRight$; } + public get leftStick (): InputSourceStick { return this._leftStick$; } + public get rightStick (): InputSourceStick { return this._rightStick$; } + public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick$; } + public get buttonRightStick (): InputSourceButton { return this._buttonRightStick$; } + public get buttonOptions (): InputSourceButton { return this._buttonOptions$; } + public get buttonStart (): InputSourceButton { return this._buttonStart$; } + public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition$; } + public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation$; } + public get handRightPosition (): InputSourcePosition { return this._handRightPosition$; } + public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation$; } + public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition$; } + public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation$; } + public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition$; } + public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation$; } + public get touchButtonA (): InputSourceTouch { return this._touchButtonA$; } + public get touchButtonB (): InputSourceTouch { return this._touchButtonB$; } + public get touchButtonX (): InputSourceTouch { return this._touchButtonX$; } + public get touchButtonY (): InputSourceTouch { return this._touchButtonY$; } + public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft$; } + public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight$; } + public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft$; } + public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight$; } private _eventTarget: EventTarget = new EventTarget(); - private declare _buttonNorth: InputSourceButton; - private declare _buttonEast: InputSourceButton; - private declare _buttonWest: InputSourceButton; - private declare _buttonSouth: InputSourceButton; - private declare _buttonTriggerLeft: InputSourceButton; - private declare _buttonTriggerRight: InputSourceButton; - private declare _triggerLeft: InputSourceButton; - private declare _triggerRight: InputSourceButton; - private declare _gripLeft: InputSourceButton; - private declare _gripRight: InputSourceButton; - private declare _leftStick: InputSourceStick; - private declare _rightStick: InputSourceStick; - private declare _buttonLeftStick: InputSourceButton; - private declare _buttonRightStick: InputSourceButton; - private declare _buttonOptions: InputSourceButton; - private declare _buttonStart: InputSourceButton; - private declare _handLeftPosition: InputSourcePosition; - private declare _handLeftOrientation: InputSourceOrientation; - private declare _handRightPosition: InputSourcePosition; - private declare _handRightOrientation: InputSourceOrientation; - private declare _aimLeftPosition: InputSourcePosition; - private declare _aimLeftOrientation: InputSourceOrientation; - private declare _aimRightPosition: InputSourcePosition; - private declare _aimRightOrientation: InputSourceOrientation; - private declare _touchButtonA: InputSourceTouch; - private declare _touchButtonB: InputSourceTouch; - private declare _touchButtonX: InputSourceTouch; - private declare _touchButtonY: InputSourceTouch; - private declare _touchButtonTriggerLeft: InputSourceTouch; - private declare _touchButtonTriggerRight: InputSourceTouch; - private declare _touchButtonThumbStickLeft: InputSourceTouch; - private declare _touchButtonThumbStickRight: InputSourceTouch; + private declare _buttonNorth$: InputSourceButton; + private declare _buttonEast$: InputSourceButton; + private declare _buttonWest$: InputSourceButton; + private declare _buttonSouth$: InputSourceButton; + private declare _buttonTriggerLeft$: InputSourceButton; + private declare _buttonTriggerRight$: InputSourceButton; + private declare _triggerLeft$: InputSourceButton; + private declare _triggerRight$: InputSourceButton; + private declare _gripLeft$: InputSourceButton; + private declare _gripRight$: InputSourceButton; + private declare _leftStick$: InputSourceStick; + private declare _rightStick$: InputSourceStick; + private declare _buttonLeftStick$: InputSourceButton; + private declare _buttonRightStick$: InputSourceButton; + private declare _buttonOptions$: InputSourceButton; + private declare _buttonStart$: InputSourceButton; + private declare _handLeftPosition$: InputSourcePosition; + private declare _handLeftOrientation$: InputSourceOrientation; + private declare _handRightPosition$: InputSourcePosition; + private declare _handRightOrientation$: InputSourceOrientation; + private declare _aimLeftPosition$: InputSourcePosition; + private declare _aimLeftOrientation$: InputSourceOrientation; + private declare _aimRightPosition$: InputSourcePosition; + private declare _aimRightOrientation$: InputSourceOrientation; + private declare _touchButtonA$: InputSourceTouch; + private declare _touchButtonB$: InputSourceTouch; + private declare _touchButtonX$: InputSourceTouch; + private declare _touchButtonY$: InputSourceTouch; + private declare _touchButtonTriggerLeft$: InputSourceTouch; + private declare _touchButtonTriggerRight$: InputSourceTouch; + private declare _touchButtonThumbStickLeft$: InputSourceTouch; + private declare _touchButtonThumbStickRight$: InputSourceTouch; constructor () { - this._initInputSource(); + this._initInputSource$(); } /** @@ -108,31 +108,31 @@ export class HandleInputDevice { this._eventTarget.on(eventType, callback, target); } - private _initInputSource (): void { - this._buttonNorth = new InputSourceButton(); - this._buttonNorth.getValue = (): number => 0; - this._buttonEast = new InputSourceButton(); - this._buttonEast.getValue = (): number => 0; - this._buttonWest = new InputSourceButton(); - this._buttonWest.getValue = (): number => 0; - this._buttonSouth = new InputSourceButton(); - this._buttonSouth.getValue = (): number => 0; - - this._buttonTriggerLeft = new InputSourceButton(); - this._buttonTriggerLeft.getValue = (): number => 0; - this._buttonTriggerRight = new InputSourceButton(); - this._buttonTriggerRight.getValue = (): number => 0; - this._triggerLeft = new InputSourceButton(); - this._triggerLeft.getValue = (): number => 0; - this._triggerRight = new InputSourceButton(); - this._triggerRight.getValue = (): number => 0; - this._gripLeft = new InputSourceButton(); - this._gripLeft.getValue = (): number => 0; - this._gripRight = new InputSourceButton(); - this._gripRight.getValue = (): number => 0; - - this._buttonLeftStick = new InputSourceButton(); - this._buttonLeftStick.getValue = (): number => 0; + private _initInputSource$ (): void { + this._buttonNorth$ = new InputSourceButton(); + this._buttonNorth$.getValue = (): number => 0; + this._buttonEast$ = new InputSourceButton(); + this._buttonEast$.getValue = (): number => 0; + this._buttonWest$ = new InputSourceButton(); + this._buttonWest$.getValue = (): number => 0; + this._buttonSouth$ = new InputSourceButton(); + this._buttonSouth$.getValue = (): number => 0; + + this._buttonTriggerLeft$ = new InputSourceButton(); + this._buttonTriggerLeft$.getValue = (): number => 0; + this._buttonTriggerRight$ = new InputSourceButton(); + this._buttonTriggerRight$.getValue = (): number => 0; + this._triggerLeft$ = new InputSourceButton(); + this._triggerLeft$.getValue = (): number => 0; + this._triggerRight$ = new InputSourceButton(); + this._triggerRight$.getValue = (): number => 0; + this._gripLeft$ = new InputSourceButton(); + this._gripLeft$.getValue = (): number => 0; + this._gripRight$ = new InputSourceButton(); + this._gripRight$.getValue = (): number => 0; + + this._buttonLeftStick$ = new InputSourceButton(); + this._buttonLeftStick$.getValue = (): number => 0; const leftStickUp = new InputSourceButton(); leftStickUp.getValue = (): number => 0; const leftStickDown = new InputSourceButton(); @@ -141,10 +141,10 @@ export class HandleInputDevice { leftStickLeft.getValue = (): number => 0; const leftStickRight = new InputSourceButton(); leftStickRight.getValue = (): number => 0; - this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); + this._leftStick$ = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight }); - this._buttonRightStick = new InputSourceButton(); - this._buttonRightStick.getValue = (): number => 0; + this._buttonRightStick$ = new InputSourceButton(); + this._buttonRightStick$.getValue = (): number => 0; const rightStickUp = new InputSourceButton(); rightStickUp.getValue = (): number => 0; const rightStickDown = new InputSourceButton(); @@ -153,48 +153,48 @@ export class HandleInputDevice { rightStickLeft.getValue = (): number => 0; const rightStickRight = new InputSourceButton(); rightStickRight.getValue = (): number => 0; - this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); - - this._buttonOptions = new InputSourceButton(); - this._buttonOptions.getValue = (): number => 0; - this._buttonStart = new InputSourceButton(); - this._buttonStart.getValue = (): number => 0; - - this._handLeftPosition = new InputSourcePosition(); - this._handLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._handLeftOrientation = new InputSourceOrientation(); - this._handLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._handRightPosition = new InputSourcePosition(); - this._handRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._handRightOrientation = new InputSourceOrientation(); - this._handRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimLeftPosition = new InputSourcePosition(); - this._aimLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimLeftOrientation = new InputSourceOrientation(); - this._aimLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._aimRightPosition = new InputSourcePosition(); - this._aimRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._aimRightOrientation = new InputSourceOrientation(); - this._aimRightOrientation.getValue = (): Readonly => Quat.IDENTITY; - - this._touchButtonA = new InputSourceTouch(); - this._touchButtonA.getValue = (): number => 0; - this._touchButtonB = new InputSourceTouch(); - this._touchButtonB.getValue = (): number => 0; - this._touchButtonX = new InputSourceTouch(); - this._touchButtonX.getValue = (): number => 0; - this._touchButtonY = new InputSourceTouch(); - this._touchButtonY.getValue = (): number => 0; - this._touchButtonTriggerLeft = new InputSourceTouch(); - this._touchButtonTriggerLeft.getValue = (): number => 0; - this._touchButtonTriggerRight = new InputSourceTouch(); - this._touchButtonTriggerRight.getValue = (): number => 0; - this._touchButtonThumbStickLeft = new InputSourceTouch(); - this._touchButtonThumbStickLeft.getValue = (): number => 0; - this._touchButtonThumbStickRight = new InputSourceTouch(); - this._touchButtonThumbStickRight.getValue = (): number => 0; + this._rightStick$ = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight }); + + this._buttonOptions$ = new InputSourceButton(); + this._buttonOptions$.getValue = (): number => 0; + this._buttonStart$ = new InputSourceButton(); + this._buttonStart$.getValue = (): number => 0; + + this._handLeftPosition$ = new InputSourcePosition(); + this._handLeftPosition$.getValue = (): Readonly => Vec3.ZERO; + this._handLeftOrientation$ = new InputSourceOrientation(); + this._handLeftOrientation$.getValue = (): Readonly => Quat.IDENTITY; + + this._handRightPosition$ = new InputSourcePosition(); + this._handRightPosition$.getValue = (): Readonly => Vec3.ZERO; + this._handRightOrientation$ = new InputSourceOrientation(); + this._handRightOrientation$.getValue = (): Readonly => Quat.IDENTITY; + + this._aimLeftPosition$ = new InputSourcePosition(); + this._aimLeftPosition$.getValue = (): Readonly => Vec3.ZERO; + this._aimLeftOrientation$ = new InputSourceOrientation(); + this._aimLeftOrientation$.getValue = (): Readonly => Quat.IDENTITY; + + this._aimRightPosition$ = new InputSourcePosition(); + this._aimRightPosition$.getValue = (): Readonly => Vec3.ZERO; + this._aimRightOrientation$ = new InputSourceOrientation(); + this._aimRightOrientation$.getValue = (): Readonly => Quat.IDENTITY; + + this._touchButtonA$ = new InputSourceTouch(); + this._touchButtonA$.getValue = (): number => 0; + this._touchButtonB$ = new InputSourceTouch(); + this._touchButtonB$.getValue = (): number => 0; + this._touchButtonX$ = new InputSourceTouch(); + this._touchButtonX$.getValue = (): number => 0; + this._touchButtonY$ = new InputSourceTouch(); + this._touchButtonY$.getValue = (): number => 0; + this._touchButtonTriggerLeft$ = new InputSourceTouch(); + this._touchButtonTriggerLeft$.getValue = (): number => 0; + this._touchButtonTriggerRight$ = new InputSourceTouch(); + this._touchButtonTriggerRight$.getValue = (): number => 0; + this._touchButtonThumbStickLeft$ = new InputSourceTouch(); + this._touchButtonThumbStickLeft$.getValue = (): number => 0; + this._touchButtonThumbStickRight$ = new InputSourceTouch(); + this._touchButtonThumbStickRight$.getValue = (): number => 0; } } diff --git a/pal/input/minigame/hmd-input.ts b/pal/input/minigame/hmd-input.ts index 20ebe8a167e..72b2ed2b233 100644 --- a/pal/input/minigame/hmd-input.ts +++ b/pal/input/minigame/hmd-input.ts @@ -29,47 +29,47 @@ import { InputSourcePosition, InputSourceOrientation } from '../input-source'; import { Vec3, Quat } from '../../../cocos/core/math'; export class HMDInputDevice { - public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; } - public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; } - public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; } - public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; } - public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; } - public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; } + public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition$; } + public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation$; } + public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition$; } + public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation$; } + public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition$; } + public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation$; } - private _eventTarget: EventTarget = new EventTarget(); + private _eventTarget$: EventTarget = new EventTarget(); - private declare _viewLeftPosition: InputSourcePosition; - private declare _viewLeftOrientation: InputSourceOrientation; - private declare _viewRightPosition: InputSourcePosition; - private declare _viewRightOrientation: InputSourceOrientation; - private declare _headMiddlePosition: InputSourcePosition; - private declare _headMiddleOrientation: InputSourceOrientation; + private declare _viewLeftPosition$: InputSourcePosition; + private declare _viewLeftOrientation$: InputSourceOrientation; + private declare _viewRightPosition$: InputSourcePosition; + private declare _viewRightOrientation$: InputSourceOrientation; + private declare _headMiddlePosition$: InputSourcePosition; + private declare _headMiddleOrientation$: InputSourceOrientation; constructor () { - this._initInputSource(); + this._initInputSource$(); } /** * @engineInternal */ public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); + this._eventTarget$.on(eventType, callback, target); } - private _initInputSource (): void { - this._viewLeftPosition = new InputSourcePosition(); - this._viewLeftPosition.getValue = (): Readonly => Vec3.ZERO; - this._viewLeftOrientation = new InputSourceOrientation(); - this._viewLeftOrientation.getValue = (): Readonly => Quat.IDENTITY; + private _initInputSource$ (): void { + this._viewLeftPosition$ = new InputSourcePosition(); + this._viewLeftPosition$.getValue = (): Readonly => Vec3.ZERO; + this._viewLeftOrientation$ = new InputSourceOrientation(); + this._viewLeftOrientation$.getValue = (): Readonly => Quat.IDENTITY; - this._viewRightPosition = new InputSourcePosition(); - this._viewRightPosition.getValue = (): Readonly => Vec3.ZERO; - this._viewRightOrientation = new InputSourceOrientation(); - this._viewRightOrientation.getValue = (): Readonly => Quat.IDENTITY; + this._viewRightPosition$ = new InputSourcePosition(); + this._viewRightPosition$.getValue = (): Readonly => Vec3.ZERO; + this._viewRightOrientation$ = new InputSourceOrientation(); + this._viewRightOrientation$.getValue = (): Readonly => Quat.IDENTITY; - this._headMiddlePosition = new InputSourcePosition(); - this._headMiddlePosition.getValue = (): Readonly => Vec3.ZERO; - this._headMiddleOrientation = new InputSourceOrientation(); - this._headMiddleOrientation.getValue = (): Readonly => Quat.IDENTITY; + this._headMiddlePosition$ = new InputSourcePosition(); + this._headMiddlePosition$.getValue = (): Readonly => Vec3.ZERO; + this._headMiddleOrientation$ = new InputSourceOrientation(); + this._headMiddleOrientation$.getValue = (): Readonly => Quat.IDENTITY; } } diff --git a/pal/input/minigame/keyboard-input.ts b/pal/input/minigame/keyboard-input.ts index c78f15e7414..8bf5e0bb16f 100644 --- a/pal/input/minigame/keyboard-input.ts +++ b/pal/input/minigame/keyboard-input.ts @@ -138,44 +138,44 @@ function getKeyCode (code: string): KeyCode { } export class KeyboardInputSource { - private _eventTarget: EventTarget = new EventTarget(); + private _eventTarget$: EventTarget = new EventTarget(); // KeyboardEvent.repeat is not supported on Wechat PC platform. - private _keyStateMap: Record = {}; + private _keyStateMap$: Record = {}; constructor () { if (systemInfo.hasFeature(Feature.EVENT_KEYBOARD)) { - this._registerEvent(); + this._registerEvent$(); } } - private _registerEvent (): void { + private _registerEvent$ (): void { minigame.wx?.onKeyDown?.((res) => { const keyCode = getKeyCode(res.code); - if (!this._keyStateMap[keyCode]) { - const eventKeyDown = this._getInputEvent(res, InputEventType.KEY_DOWN); - this._eventTarget.emit(InputEventType.KEY_DOWN, eventKeyDown); + if (!this._keyStateMap$[keyCode]) { + const eventKeyDown = this._getInputEvent$(res, InputEventType.KEY_DOWN); + this._eventTarget$.emit(InputEventType.KEY_DOWN, eventKeyDown); } else { - const eventKeyPressing = this._getInputEvent(res, InputEventType.KEY_PRESSING); - this._eventTarget.emit(InputEventType.KEY_PRESSING, eventKeyPressing); + const eventKeyPressing = this._getInputEvent$(res, InputEventType.KEY_PRESSING); + this._eventTarget$.emit(InputEventType.KEY_PRESSING, eventKeyPressing); } - this._keyStateMap[keyCode] = true; + this._keyStateMap$[keyCode] = true; }); minigame.wx?.onKeyUp?.((res) => { const keyCode = getKeyCode(res.code); - const eventKeyUp = this._getInputEvent(res, InputEventType.KEY_UP); - this._keyStateMap[keyCode] = false; - this._eventTarget.emit(InputEventType.KEY_UP, eventKeyUp); + const eventKeyUp = this._getInputEvent$(res, InputEventType.KEY_UP); + this._keyStateMap$[keyCode] = false; + this._eventTarget$.emit(InputEventType.KEY_UP, eventKeyUp); }); } - private _getInputEvent (event: KeyboardEventData, eventType: InputEventType): EventKeyboard { + private _getInputEvent$ (event: KeyboardEventData, eventType: InputEventType): EventKeyboard { const keyCode = getKeyCode(event.code); const eventKeyboard = new EventKeyboard(keyCode, eventType); return eventKeyboard; } public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); + this._eventTarget$.on(eventType, callback, target); } } diff --git a/pal/input/minigame/mouse-input.ts b/pal/input/minigame/mouse-input.ts index e05970b8572..7cffe0fe027 100644 --- a/pal/input/minigame/mouse-input.ts +++ b/pal/input/minigame/mouse-input.ts @@ -33,17 +33,17 @@ import { InputEventType } from '../../../cocos/input/types/event-enum'; import { Feature } from '../../system-info/enum-type'; export class MouseInputSource { - private _eventTarget: EventTarget = new EventTarget(); - private _isPressed = false; - private _preMousePos: Vec2 = new Vec2(); + private _eventTarget$: EventTarget = new EventTarget(); + private _isPressed$ = false; + private _preMousePos$: Vec2 = new Vec2(); constructor () { if (systemInfo.hasFeature(Feature.EVENT_MOUSE)) { - this._registerEvent(); + this._registerEvent$(); } } - private _getLocation (event: MouseEventData): Vec2 { + private _getLocation$ (event: MouseEventData): Vec2 { const windowSize = screenAdapter.windowSize; const dpr = screenAdapter.devicePixelRatio; const x = event.x * dpr; @@ -51,26 +51,26 @@ export class MouseInputSource { return new Vec2(x, y); } - private _registerEvent (): void { - minigame.wx?.onMouseDown?.(this._createCallback(InputEventType.MOUSE_DOWN)); - minigame.wx?.onMouseMove?.(this._createCallback(InputEventType.MOUSE_MOVE)); - minigame.wx?.onMouseUp?.(this._createCallback(InputEventType.MOUSE_UP)); - minigame.wx?.onWheel?.(this._handleMouseWheel.bind(this)); + private _registerEvent$ (): void { + minigame.wx?.onMouseDown?.(this._createCallback$(InputEventType.MOUSE_DOWN)); + minigame.wx?.onMouseMove?.(this._createCallback$(InputEventType.MOUSE_MOVE)); + minigame.wx?.onMouseUp?.(this._createCallback$(InputEventType.MOUSE_UP)); + minigame.wx?.onWheel?.(this._handleMouseWheel$.bind(this)); } - private _createCallback (eventType: InputEventType) { + private _createCallback$ (eventType: InputEventType) { return (event: MouseEventData): void => { - const location = this._getLocation(event); + const location = this._getLocation$(event); let button = event.button; switch (eventType) { case InputEventType.MOUSE_DOWN: - this._isPressed = true; + this._isPressed$ = true; break; case InputEventType.MOUSE_UP: - this._isPressed = false; + this._isPressed$ = false; break; case InputEventType.MOUSE_MOVE: - if (!this._isPressed) { + if (!this._isPressed$) { button = EventMouse.BUTTON_MISSING; } break; @@ -78,36 +78,36 @@ export class MouseInputSource { break; } - const eventMouse = new EventMouse(eventType, false, this._preMousePos); + const eventMouse = new EventMouse(eventType, false, this._preMousePos$); eventMouse.setLocation(location.x, location.y); eventMouse.setButton(button); - eventMouse.movementX = location.x - this._preMousePos.x; - eventMouse.movementY = this._preMousePos.y - location.y; + eventMouse.movementX = location.x - this._preMousePos$.x; + eventMouse.movementY = this._preMousePos$.y - location.y; // update previous mouse position. - this._preMousePos.set(location.x, location.y); - this._eventTarget.emit(eventType, eventMouse); + this._preMousePos$.set(location.x, location.y); + this._eventTarget$.emit(eventType, eventMouse); }; } - private _handleMouseWheel (event: MouseWheelEventData): void { + private _handleMouseWheel$ (event: MouseWheelEventData): void { const eventType = InputEventType.MOUSE_WHEEL; - const location = this._getLocation(event); + const location = this._getLocation$(event); const button = event.button; - const eventMouse = new EventMouse(eventType, false, this._preMousePos); + const eventMouse = new EventMouse(eventType, false, this._preMousePos$); eventMouse.setLocation(location.x, location.y); eventMouse.setButton(button); - eventMouse.movementX = location.x - this._preMousePos.x; - eventMouse.movementY = this._preMousePos.y - location.y; + eventMouse.movementX = location.x - this._preMousePos$.x; + eventMouse.movementY = this._preMousePos$.y - location.y; eventMouse.setScrollData(event.deltaX, -event.deltaY); // update previous mouse position. - this._preMousePos.set(location.x, location.y); - this._eventTarget.emit(InputEventType.MOUSE_WHEEL, eventMouse); + this._preMousePos$.set(location.x, location.y); + this._eventTarget$.emit(InputEventType.MOUSE_WHEEL, eventMouse); } public on (eventType: InputEventType, callback: MouseCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); + this._eventTarget$.on(eventType, callback, target); } } diff --git a/pal/input/minigame/touch-input.ts b/pal/input/minigame/touch-input.ts index 511f35481a4..cd5ce773b0b 100644 --- a/pal/input/minigame/touch-input.ts +++ b/pal/input/minigame/touch-input.ts @@ -26,32 +26,30 @@ import { TouchCallback } from 'pal/input'; import { minigame } from 'pal/minigame'; import { screenAdapter } from 'pal/screen-adapter'; import { systemInfo } from 'pal/system-info'; -import { ALIPAY, VIVO } from 'internal:constants'; import { Size, Vec2 } from '../../../cocos/core/math'; import { EventTarget } from '../../../cocos/core/event'; import { EventTouch, Touch } from '../../../cocos/input/types'; import { touchManager } from '../touch-manager'; -import { macro } from '../../../cocos/core/platform/macro'; import { InputEventType } from '../../../cocos/input/types/event-enum'; import { Feature } from '../../system-info/enum-type'; export class TouchInputSource { - private _eventTarget: EventTarget = new EventTarget(); + private _eventTarget$: EventTarget = new EventTarget(); constructor () { if (systemInfo.hasFeature(Feature.INPUT_TOUCH)) { - this._registerEvent(); + this._registerEvent$(); } } - private _registerEvent (): void { - minigame.onTouchStart(this._createCallback(InputEventType.TOUCH_START)); - minigame.onTouchMove(this._createCallback(InputEventType.TOUCH_MOVE)); - minigame.onTouchEnd(this._createCallback(InputEventType.TOUCH_END)); - minigame.onTouchCancel(this._createCallback(InputEventType.TOUCH_CANCEL)); + private _registerEvent$ (): void { + minigame.onTouchStart(this._createCallback$(InputEventType.TOUCH_START)); + minigame.onTouchMove(this._createCallback$(InputEventType.TOUCH_MOVE)); + minigame.onTouchEnd(this._createCallback$(InputEventType.TOUCH_END)); + minigame.onTouchCancel(this._createCallback$(InputEventType.TOUCH_CANCEL)); } - private _createCallback (eventType: InputEventType) { + private _createCallback$ (eventType: InputEventType) { return (event: TouchEvent): void => { const handleTouches: Touch[] = []; const windowSize = screenAdapter.windowSize; @@ -63,7 +61,7 @@ export class TouchInputSource { if (touchID === null) { continue; } - const location = this._getLocation(changedTouch, windowSize, dpr); + const location = this._getLocation$(changedTouch, windowSize, dpr); const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y); if (!touch) { continue; @@ -80,18 +78,18 @@ export class TouchInputSource { eventType, touchManager.getAllTouches(), ); - this._eventTarget.emit(eventType, eventTouch); + this._eventTarget$.emit(eventType, eventTouch); } }; } - private _getLocation (touch: globalThis.Touch, windowSize: Size, dpr: number): Vec2 { + private _getLocation$ (touch: globalThis.Touch, windowSize: Size, dpr: number): Vec2 { const x = touch.clientX * dpr; const y = windowSize.height - touch.clientY * dpr; return new Vec2(x, y); } public on (eventType: InputEventType, callback: TouchCallback, target?: any): void { - this._eventTarget.on(eventType, callback, target); + this._eventTarget$.on(eventType, callback, target); } } diff --git a/pal/input/touch-manager.ts b/pal/input/touch-manager.ts index 930135dadb8..2434f5b31b6 100644 --- a/pal/input/touch-manager.ts +++ b/pal/input/touch-manager.ts @@ -23,7 +23,7 @@ */ import { Vec2 } from '../../cocos/core/math/vec2'; -import { log } from '../../cocos/core/platform/debug'; +import { logID } from '../../cocos/core/platform/debug'; import { macro } from '../../cocos/core/platform/macro'; import { Touch } from '../../cocos/input/types'; @@ -52,12 +52,12 @@ class TouchManager { */ private _createTouch (touchID: number, x: number, y: number): Touch | undefined { if (this._touchMap.has(touchID)) { - log('Cannot create the same touch object.'); + logID(2301); return undefined; } const checkResult = this._checkTouchMapSizeMoreThanMax(touchID); if (checkResult) { - log('The touches is more than MAX_TOUCHES.'); // TODO: logID 2300 + logID(2300); return undefined; } const touch = new Touch(x, y, touchID); @@ -147,7 +147,7 @@ class TouchManager { const now = performance.now(); this._touchMap.forEach((touch) => { if (now - touch.lastModified > macro.TOUCH_TIMEOUT) { - log(`The touches is more than MAX_TOUCHES, release touch id ${touch.getID()}.`); + logID(2302, touch.getID()); // TODO: need to handle touch cancel event when exceed the max number of touches ? this.releaseTouch(touch.getID()); } diff --git a/pal/pacer/pacer-minigame.ts b/pal/pacer/pacer-minigame.ts index a3b99ab2fa7..27903f9a85d 100644 --- a/pal/pacer/pacer-minigame.ts +++ b/pal/pacer/pacer-minigame.ts @@ -27,32 +27,32 @@ import { assertIsTrue } from '../../cocos/core/data/utils/asserts'; import { checkPalIntegrity, withImpl } from '../integrity-check'; export class Pacer { - private _rafHandle = 0; - private _onTick: (() => void) | null = null; - private declare _updateCallback: () => void; - private _targetFrameRate = 60; - private _isPlaying = false; + private _rafHandle$ = 0; + private _onTick$: (() => void) | null = null; + private declare _updateCallback$: () => void; + private _targetFrameRate$ = 60; + private _isPlaying$ = false; constructor () { - this._updateCallback = (): void => { - if (this._isPlaying) { - this._rafHandle = requestAnimationFrame(this._updateCallback); + this._updateCallback$ = (): void => { + if (this._isPlaying$) { + this._rafHandle$ = requestAnimationFrame(this._updateCallback$); } - if (this._onTick) { - this._onTick(); + if (this._onTick$) { + this._onTick$(); } }; } get targetFrameRate (): number { - return this._targetFrameRate; + return this._targetFrameRate$; } set targetFrameRate (val: number) { - if (this._targetFrameRate !== val) { + if (this._targetFrameRate$ !== val) { assertIsTrue(val > 0); - this._targetFrameRate = val; - minigame.setPreferredFramesPerSecond(this._targetFrameRate); - if (this._isPlaying) { + this._targetFrameRate$ = val; + minigame.setPreferredFramesPerSecond(this._targetFrameRate$); + if (this._isPlaying$) { this.stop(); this.start(); } @@ -60,24 +60,24 @@ export class Pacer { } set onTick (val: (() => void) | null) { - this._onTick = val; + this._onTick$ = val; } get onTick (): (() => void) | null { - return this._onTick; + return this._onTick$; } start (): void { - if (this._isPlaying) return; - this._rafHandle = requestAnimationFrame(this._updateCallback); - this._isPlaying = true; + if (this._isPlaying$) return; + this._rafHandle$ = requestAnimationFrame(this._updateCallback$); + this._isPlaying$ = true; } stop (): void { - if (!this._isPlaying) return; - cancelAnimationFrame(this._rafHandle); - this._rafHandle = 0; - this._isPlaying = false; + if (!this._isPlaying$) return; + cancelAnimationFrame(this._rafHandle$); + this._rafHandle$ = 0; + this._isPlaying$ = false; } } diff --git a/pal/screen-adapter/enum-type/orientation.ts b/pal/screen-adapter/enum-type/orientation.ts index 858b7a5e52e..f1dff3d14fb 100644 --- a/pal/screen-adapter/enum-type/orientation.ts +++ b/pal/screen-adapter/enum-type/orientation.ts @@ -22,18 +22,11 @@ THE SOFTWARE. */ -const _PORTRAIT = 1; -const _PORTRAIT_UPSIDE_DOWN = _PORTRAIT << 1; -const _LEFT = _PORTRAIT << 2; -const _RIGHT = _PORTRAIT << 3; -const _LANDSCAPE = _LEFT | _RIGHT; -const _AUTO = _PORTRAIT | _LANDSCAPE; - export enum Orientation { - PORTRAIT = _PORTRAIT, - PORTRAIT_UPSIDE_DOWN = _PORTRAIT_UPSIDE_DOWN, - LANDSCAPE_LEFT = _LEFT, - LANDSCAPE_RIGHT = _RIGHT, - LANDSCAPE = _LANDSCAPE, - AUTO = _AUTO, + PORTRAIT = 1, + PORTRAIT_UPSIDE_DOWN = PORTRAIT << 1, + LANDSCAPE_LEFT = PORTRAIT << 2, + LANDSCAPE_RIGHT = PORTRAIT << 3, + LANDSCAPE = LANDSCAPE_LEFT | LANDSCAPE_RIGHT, + AUTO = PORTRAIT | LANDSCAPE, } diff --git a/pal/system-info/minigame/system-info.ts b/pal/system-info/minigame/system-info.ts index 6b5f3d9d861..884af43c8d3 100644 --- a/pal/system-info/minigame/system-info.ts +++ b/pal/system-info/minigame/system-info.ts @@ -113,8 +113,8 @@ class SystemInfo extends EventTarget { public declare readonly browserType: BrowserType; public declare readonly browserVersion: string; public declare readonly isXR: boolean; - private declare _featureMap: IFeatureMap; - private _initPromise: Promise[] = []; + private declare _featureMap$: IFeatureMap; + private _initPromise$: Promise[] = []; constructor () { super(); @@ -198,7 +198,7 @@ class SystemInfo extends EventTarget { return false; })(); - this._featureMap = { + this._featureMap$ = { [Feature.WEBP]: false, // Initialize in Promise, [Feature.IMAGE_BITMAP]: false, [Feature.WEB_VIEW]: false, @@ -218,21 +218,21 @@ class SystemInfo extends EventTarget { [Feature.WASM]: supportWasm, }; - this._initPromise.push(this._supportsWebpPromise()); + this._initPromise$.push(this._supportsWebpPromise$()); - this._registerEvent(); + this._registerEvent$(); } - private _supportsWebpPromise (): Promise { + private _supportsWebpPromise$ (): Promise { if (!TEST) { - return this._supportsWebp().then((isSupport) => { - this._setFeature(Feature.WEBP, isSupport); + return this._supportsWebp$().then((isSupport) => { + this._setFeature$(Feature.WEBP, isSupport); }); } return Promise.resolve(); } - private _supportsWebp (): Promise { + private _supportsWebp$ (): Promise { return new Promise((resolve, reject) => { if (WECHAT_MINI_PROGRAM) { resolve(true); @@ -268,7 +268,7 @@ class SystemInfo extends EventTarget { }); } - private _registerEvent (): void { + private _registerEvent$ (): void { minigame.onHide((): void => { this.emit('hide'); }); @@ -277,16 +277,16 @@ class SystemInfo extends EventTarget { }); } - private _setFeature (feature: Feature, value: boolean): boolean { - return this._featureMap[feature] = value; + private _setFeature$ (feature: Feature, value: boolean): boolean { + return this._featureMap$[feature] = value; } public init (): Promise { - return Promise.all(this._initPromise); + return Promise.all(this._initPromise$); } public hasFeature (feature: Feature): boolean { - return this._featureMap[feature]; + return this._featureMap$[feature]; } public getBatteryLevel (): number { diff --git a/platforms/minigame/common/engine/Editbox.js b/platforms/minigame/common/engine/Editbox.js index 3097bf74f48..8bd0372f265 100644 --- a/platforms/minigame/common/engine/Editbox.js +++ b/platforms/minigame/common/engine/Editbox.js @@ -24,8 +24,9 @@ return 'go'; case KeyboardReturnType.NEXT: return 'next'; + default: + return 'done'; } - return 'done'; } function MiniGameEditBoxImpl () { diff --git a/scripts/build-debug-infos.js b/scripts/build-debug-infos.js index f56da4947af..66a318e923f 100644 --- a/scripts/build-debug-infos.js +++ b/scripts/build-debug-infos.js @@ -29,6 +29,7 @@ function buildDebugInfos () { const writeContent = JSON.stringify(debugInfos, null, 4); writeFileSync('DebugInfos.json', writeContent); + console.log(magenta(`${prefix} DONE! ${prefix}`)); } buildDebugInfos(); diff --git a/tests/asset-manager/finalizer.test.ts b/tests/asset-manager/finalizer.test.ts index 33145019bf3..5caa61ebf5c 100644 --- a/tests/asset-manager/finalizer.test.ts +++ b/tests/asset-manager/finalizer.test.ts @@ -28,7 +28,7 @@ describe('releaseManager', () => { assetManager.assets.add('AAA', tex); expect(isValid(tex, true)).toBeTruthy(); // @ts-ignore - releaseManager._free(tex, false); + releaseManager._free$(tex, false); expect(assetManager.assets.count).toBe(1); expect(isValid(tex, true)).toBeTruthy(); assetManager.releaseAsset(tex); @@ -46,7 +46,7 @@ describe('releaseManager', () => { assetManager.assets.add('BBB', texB); assetManager.dependUtil._depends.add('AAA', {deps: ['BBB']}); // @ts-ignore - releaseManager._free(texA); + releaseManager._free$(texA); expect(assetManager.assets.count).toBe(0); }); @@ -73,7 +73,7 @@ describe('releaseManager', () => { assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'DDD']}); assetManager.dependUtil._depends.add('DDD', {deps: ['BBB']}); // @ts-ignore - releaseManager._free(texA); + releaseManager._free$(texA); expect(assetManager.assets.count).toBe(0); }); @@ -101,7 +101,7 @@ describe('releaseManager', () => { assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'DDD']}); assetManager.dependUtil._depends.add('DDD', {deps: ['BBB']}); // @ts-ignore - releaseManager._free(texA); + releaseManager._free$(texA); expect(assetManager.assets.count).toBe(4); assetManager.releaseAll(); }); @@ -128,7 +128,7 @@ describe('releaseManager', () => { assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'BBB']}); assetManager.dependUtil._depends.add('DDD', {deps: ['AAA']}); // @ts-ignore - releaseManager._free(texA); + releaseManager._free$(texA); expect(assetManager.assets.count).toBe(0); }); @@ -154,7 +154,7 @@ describe('releaseManager', () => { assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'BBB']}); assetManager.dependUtil._depends.add('DDD', {deps: ['AAA']}); // @ts-ignore - releaseManager._free(texA); + releaseManager._free$(texA); expect(assetManager.assets.count).toBe(4); assetManager.releaseAll(); }); @@ -181,7 +181,7 @@ describe('releaseManager', () => { assetManager.dependUtil._depends.add('CCC', {deps: ['DDD']}); assetManager.dependUtil._depends.add('DDD', {deps: ['AAA']}); // @ts-ignore - releaseManager._free(texA); + releaseManager._free$(texA); expect(assetManager.assets.count).toBe(0); assetManager.releaseAll(); @@ -215,7 +215,7 @@ describe('releaseManager', () => { assetManager.dependUtil._depends.add('scene 2', {deps: ['BBB', 'CCC']}); releaseManager._autoRelease(scene1, scene2, {}); // @ts-expect-error set private property - releaseManager._freeAssets(); + releaseManager._freeAssets$(); expect(assetManager.assets.count).toBe(2); expect(texB.refCount).toBe(1); expect(texC.refCount).toBe(1); @@ -236,7 +236,7 @@ describe('releaseManager', () => { expect(assetManager.assets.count).toBe(1); releaseManager._autoRelease(scene1, scene2, {}); // @ts-expect-error set private property - releaseManager._freeAssets(); + releaseManager._freeAssets$(); expect(assetManager.assets.count).toBe(0); }); @@ -266,7 +266,7 @@ describe('releaseManager', () => { assetManager.dependUtil._depends.add('scene 2', {deps: []}); releaseManager._autoRelease(scene1, scene2, persistNodes); // @ts-expect-error set private property - releaseManager._freeAssets(); + releaseManager._freeAssets$(); expect(assetManager.assets.count).toBe(1); expect(assetManager.assets.get('AAA')).toBe(sp); expect(sp.refCount).toBe(2); @@ -274,7 +274,7 @@ describe('releaseManager', () => { expect(sp.refCount).toBe(1); releaseManager._autoRelease(scene2, scene3, {}); // @ts-expect-error set private property - releaseManager._freeAssets(); + releaseManager._freeAssets$(); expect(assetManager.assets.count).toBe(0); }); @@ -285,7 +285,7 @@ describe('releaseManager', () => { assetManager.assets.add('TestDontDestroy', tex); expect(isValid(tex, true)).toBeTruthy(); // @ts-ignore - releaseManager._free(tex, false); + releaseManager._free$(tex, false); expect(assetManager.assets.count).toBe(1); expect(isValid(tex, true)).toBeTruthy(); assetManager.releaseAsset(tex); diff --git a/tests/core/memop/container-manager.test.ts b/tests/core/memop/container-manager.test.ts index f83cf10d3a6..42af5602747 100644 --- a/tests/core/memop/container-manager.test.ts +++ b/tests/core/memop/container-manager.test.ts @@ -9,55 +9,55 @@ class TestContainer extends ScalableContainer { test('container', () => { // @ts-expect-error - scalableContainerManager._pools.length = 0; + scalableContainerManager._pools$.length = 0; const testContainer = new TestContainer(); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools$.length).toBe(1); expect(testContainer._poolHandle).toBe(0); scalableContainerManager.addContainer(testContainer); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools$.length).toBe(1); expect(testContainer._poolHandle).toBe(0); const testContainer1 = new TestContainer(); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(2); + expect(scalableContainerManager._pools$.length).toBe(2); expect(testContainer1._poolHandle).toBe(1); testContainer.destroy(); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools$.length).toBe(1); expect(testContainer._poolHandle).toBe(-1); expect(testContainer1._poolHandle).toBe(0); const testContainer2 = new TestContainer(); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(2); + expect(scalableContainerManager._pools$.length).toBe(2); expect(testContainer2._poolHandle).toBe(1); testContainer2.destroy(); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(1); + expect(scalableContainerManager._pools$.length).toBe(1); expect(testContainer2._poolHandle).toBe(-1); expect(testContainer1._poolHandle).toBe(0); testContainer1.destroy(); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(0); + expect(scalableContainerManager._pools$.length).toBe(0); expect(testContainer2._poolHandle).toBe(-1); expect(testContainer1._poolHandle).toBe(-1); expect(testContainer._poolHandle).toBe(-1); scalableContainerManager.removeContainer(testContainer1); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBe(0); + expect(scalableContainerManager._pools$.length).toBe(0); }); test('shrink', () => { // @ts-expect-error - scalableContainerManager._pools.length = 0; + scalableContainerManager._pools$.length = 0; const testContainer = new TestContainer(); expect(testContainer.calledTimes).toBe(0); diff --git a/tests/core/memop/pool.test.ts b/tests/core/memop/pool.test.ts index a2f07a17ab1..e56fe47bb80 100644 --- a/tests/core/memop/pool.test.ts +++ b/tests/core/memop/pool.test.ts @@ -57,7 +57,7 @@ test('shrink', () => { // Pool available size is 10, less than 30, so will not free any object. pool.tryShrink(); // @ts-expect-error - expect(pool._nextAvail).toEqual(9); + expect(pool._nextAvail$).toEqual(9); calledTimes = 0; @@ -69,7 +69,7 @@ test('shrink', () => { pool.freeArray(test); pool.tryShrink(); // @ts-expect-error - expect(pool._nextAvail).toEqual(29); + expect(pool._nextAvail$).toEqual(29); calledTimes = 30; // Pool available size is 50, but its length is 60, so it will shrink 10 elements. @@ -83,7 +83,7 @@ test('shrink', () => { pool.tryShrink(); calledTimes = 10; // @ts-expect-error - expect(pool._nextAvail).toEqual(39); + expect(pool._nextAvail$).toEqual(39); // No matter shrink how many times, pool size will not less then shrinkThreshold. pool.tryShrink(); @@ -91,21 +91,21 @@ test('shrink', () => { pool.tryShrink(); pool.tryShrink(); // @ts-expect-error - expect(pool._nextAvail).toEqual(29); + expect(pool._nextAvail$).toEqual(29); }); test('destroy', () => { calledTimes = 0; // @ts-expect-error - const beforeDestroy = pool._nextAvail; + const beforeDestroy = pool._nextAvail$; // @ts-expect-error - expect(pool._nextAvail).toBeGreaterThan(0); + expect(pool._nextAvail$).toBeGreaterThan(0); pool.destroy(); expect(calledTimes).toBe(beforeDestroy + 1); // @ts-expect-error - expect(pool._nextAvail).toBe(-1); + expect(pool._nextAvail$).toBe(-1); // @ts-expect-error - expect(pool._freePool.length).toBe(0); + expect(pool._freePool$.length).toBe(0); }); \ No newline at end of file diff --git a/tests/core/settings.test.ts b/tests/core/settings.test.ts index 680dbd11598..fd236d20734 100644 --- a/tests/core/settings.test.ts +++ b/tests/core/settings.test.ts @@ -12,7 +12,7 @@ describe('Settings', () => { test('base', () => { const settings = new Settings(); // @ts-expect-error access private property - settings._settings = { + settings._settings$ = { assets: { preloadBundles: [{ bundle: 'asddda' }, { bundle: 'internal' }], preloadAssets: ['sdd1ssq', 'hjiepoqd'], diff --git a/tests/particle/renderer.test.ts b/tests/particle/renderer.test.ts index 089584b3dd3..72489310819 100644 --- a/tests/particle/renderer.test.ts +++ b/tests/particle/renderer.test.ts @@ -10,15 +10,15 @@ test('recycle pool release', () => { scene.addChild(node); game.step(); // @ts-expect-error access private property - const beforeLength = scalableContainerManager._pools.length; + const beforeLength = scalableContainerManager._pools$.length; const comp = node.addComponent(ParticleSystem); game.step(); // @ts-expect-error access private property - const currentLength = scalableContainerManager._pools.length; + const currentLength = scalableContainerManager._pools$.length; expect(currentLength).toBeGreaterThan(beforeLength); comp.destroy(); game.step(); // @ts-expect-error - expect(scalableContainerManager._pools.length).toBeLessThan(currentLength); + expect(scalableContainerManager._pools$.length).toBeLessThan(currentLength); }); \ No newline at end of file diff --git a/tests/physics2d/scene-query.ts b/tests/physics2d/scene-query.ts index 585832e2ae4..140ab68a056 100644 --- a/tests/physics2d/scene-query.ts +++ b/tests/physics2d/scene-query.ts @@ -26,7 +26,7 @@ export default function (parent: Node, _steps = 0) { nodeCollider2.worldPosition = initPos2; const body2 = nodeCollider2.addComponent(physics2d.RigidBody2D) as physics2d.RigidBody2D; const collider2 = nodeCollider2.addComponent(physics2d.BoxCollider2D) as physics2d.Collider2D; - collider2.group = physics2d.PhysicsGroup.DEFAULT; + collider2.group = physics2d.PhysicsGroup2D.DEFAULT; //test raycast cloest { @@ -65,7 +65,7 @@ export default function (parent: Node, _steps = 0) { const p0 = new Vec2(0, 0); const p1 = new Vec2(20, 0); const type = physics2d.ERaycast2DType.All; - const mask = physics2d.PhysicsGroup.DEFAULT; + const mask = physics2d.PhysicsGroup2D.DEFAULT; let result = physics2d.PhysicsSystem2D.instance.raycast(p0, p1, type, mask); expect(result.length).toBe(1); expect(result[0].collider.uuid).toBe(collider2.uuid); diff --git a/tests/tween/tween.test.ts b/tests/tween/tween.test.ts index 323b5a06953..cad49dde41f 100644 --- a/tests/tween/tween.test.ts +++ b/tests/tween/tween.test.ts @@ -75,7 +75,7 @@ test('to/by ITweenOption no type', function () { test('different targets in parallel', function () { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; @@ -145,7 +145,7 @@ test('different targets in parallel', function () { test('Test different target in sequence', function() { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; @@ -241,7 +241,7 @@ test('Test different target in sequence', function() { test('Test different target in then', function() { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; @@ -331,7 +331,7 @@ test('Test different target in then', function() { test('Test different target in clone/then', function() { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; @@ -457,7 +457,7 @@ test('Test different target in clone/then', function() { test('Test different target in clone2', function() { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; @@ -523,7 +523,7 @@ test('Test different target in clone2', function() { test('Test different target in re-target', function() { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; @@ -583,7 +583,7 @@ test('Test different target in re-target', function() { test('Test different target in nest sequence 1', function() { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; @@ -813,7 +813,7 @@ test('Test different target, union, repeat with embed tween', function() { test('Test different target in nest sequence 2', function() { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const sys = new TweenSystem(); (TweenSystem.instance as any) = sys; diff --git a/tests/ui/sprite.test.ts b/tests/ui/sprite.test.ts index b05a02d2ee8..ecad900f0ac 100644 --- a/tests/ui/sprite.test.ts +++ b/tests/ui/sprite.test.ts @@ -8,7 +8,7 @@ import { Batcher2D } from "../../cocos/2d/renderer/batcher-2d"; test('sprite.updateWorldMatrix', () => { // @ts-expect-error - director.root!._batcher = new Batcher2D(director.root!); + director.root!._batcher$ = new Batcher2D(director.root!); const scene = new Scene('test'); director.runSceneImmediate(scene);