mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-19 14:52:40 +08:00
[v3.8.5] Support inline enum and mangle private variables to reduce engine size. (#17703)
This commit is contained in:
+17
-1
@@ -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
|
||||
+8
-1
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<TFunction extends (...any) => void> (type: EventType, callback: TFunction, thisArg?: any, once?: boolean): TFunction {
|
||||
public on<TFunction extends (...any) => 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<TFunction extends (...any) => void> (type: EventType, callback: TFunction, thisArg?: any): TFunction {
|
||||
public once<TFunction extends (...any) => 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_;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<string, Asset> = {};
|
||||
@@ -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<string[]>(Settings.Category.ENGINE, 'builtinAssets');
|
||||
const builtinAssets = settings.querySettings<string[]>(SettingsCategory.ENGINE, 'builtinAssets');
|
||||
const builtinBundle = new Bundle();
|
||||
builtinBundle.init({
|
||||
name: BuiltinBundleName.INTERNAL,
|
||||
@@ -314,7 +315,7 @@ export class BuiltinResMgr {
|
||||
* @internal
|
||||
*/
|
||||
public loadBuiltinAssets (): Promise<void> {
|
||||
const builtinAssets = settings.querySettings<string[]>(Settings.Category.ENGINE, 'builtinAssets');
|
||||
const builtinAssets = settings.querySettings<string[]>(SettingsCategory.ENGINE, 'builtinAssets');
|
||||
if (TEST || !builtinAssets) return Promise.resolve();
|
||||
const resources = this._resources;
|
||||
return new Promise<void>((resolve, reject): void => {
|
||||
|
||||
@@ -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<Asset> | 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<Asset> | 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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, string[]>): void {
|
||||
private _initPath$ (pathList: Record<string, string[]>): void {
|
||||
if (!pathList) { return; }
|
||||
const paths = this.paths;
|
||||
paths.clear();
|
||||
@@ -369,7 +369,7 @@ export default class Config {
|
||||
}
|
||||
}
|
||||
|
||||
private _initScene (sceneList: Record<string, string>): void {
|
||||
private _initScene$ (sceneList: Record<string, string>): void {
|
||||
if (!sceneList) { return; }
|
||||
const scenes = this.scenes;
|
||||
scenes.clear();
|
||||
@@ -382,7 +382,7 @@ export default class Config {
|
||||
}
|
||||
}
|
||||
|
||||
private _initPackage (packageList: Record<string, string[]>): void {
|
||||
private _initPackage$ (packageList: Record<string, string[]>): 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) {
|
||||
|
||||
@@ -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<string, any>, depends: string[]): void {
|
||||
private _descend$ (uuid: string, exclude: Record<string, any>, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string, boolean> = 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<T>,
|
||||
): any;
|
||||
public loadRes<T extends Asset> (
|
||||
url: string, type?: Constructor<T> | LoadCompleteCallback<T> | LoadProgressCallback,
|
||||
url: string,
|
||||
type?: Constructor<T> | LoadCompleteCallback<T> | LoadProgressCallback,
|
||||
progressCallback?: LoadProgressCallback | LoadCompleteCallback<T>,
|
||||
completeCallback?: LoadCompleteCallback<T>,
|
||||
): 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<T>);
|
||||
completeCallback as LoadCompleteCallback<T>,
|
||||
);
|
||||
const extname = path.extname(url);
|
||||
if (extname && !resources.getInfoWithPath(url, _type)) {
|
||||
// strip extname
|
||||
@@ -355,9 +358,11 @@ export class CCLoader {
|
||||
progressCallback?: LoadProgressCallback,
|
||||
completeCallback?: LoadCompleteCallback<T[]>,
|
||||
): void {
|
||||
const { type: _type, onProgress, onComplete } = this._parseLoadResArgs<LoadCompleteCallback<Asset[]>>(type as any,
|
||||
const { type: _type, onProgress, onComplete } = this._parseLoadResArgs$<LoadCompleteCallback<Asset[]>>(
|
||||
type as any,
|
||||
progressCallback as LoadProgressCallback,
|
||||
completeCallback as LoadCompleteCallback<Asset[]>);
|
||||
completeCallback as LoadCompleteCallback<Asset[]>,
|
||||
);
|
||||
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<T>,
|
||||
completeCallback?: LoadDirCompleteCallback<T>,
|
||||
): any {
|
||||
const { type: _type, onProgress, onComplete } = this._parseLoadResArgs<LoadDirCompleteCallback<Asset>>(type as any,
|
||||
const { type: _type, onProgress, onComplete } = this._parseLoadResArgs$<LoadDirCompleteCallback<Asset>>(
|
||||
type as any,
|
||||
progressCallback as LoadProgressCallback,
|
||||
completeCallback as LoadDirCompleteCallback<Asset>);
|
||||
completeCallback as LoadDirCompleteCallback<Asset>,
|
||||
);
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, DownloadHandler> = {
|
||||
private _downloaders$: Record<string, DownloadHandler> = {
|
||||
// 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<string, string> = {}, 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<string, any>, 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string>(Settings.Category.PATH, 'previewServer') || '';
|
||||
previewServer = settings.querySettings<string>(SettingsCategory.PATH, 'previewServer') || '';
|
||||
assert(Boolean(previewServer));
|
||||
}
|
||||
text = await fetchText(`${previewServer}/query-extname/${uuid}`) as string;
|
||||
|
||||
@@ -96,9 +96,9 @@ function createBundle (id: string, data: IConfigOption, options: Record<string,
|
||||
}
|
||||
|
||||
export class Factory {
|
||||
private _creating = new Cache<((err: Error | null, data?: any | null) => void)[]>();
|
||||
private _creating$ = new Cache<((err: Error | null, data?: any | null) => void)[]>();
|
||||
|
||||
private _producers: Record<string, CreateHandler> = {
|
||||
private _producers$: Record<string, CreateHandler> = {
|
||||
// Images
|
||||
'.png': createImageAsset,
|
||||
'.jpg': createImageAsset,
|
||||
@@ -141,32 +141,32 @@ export class Factory {
|
||||
|
||||
public register (type: string | Record<string, CreateHandler>, 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<string, any>, 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;
|
||||
}
|
||||
|
||||
@@ -53,8 +53,8 @@ interface IUnpackRequest {
|
||||
*
|
||||
*/
|
||||
export class PackManager {
|
||||
private _loading = new Cache<IUnpackRequest[]>();
|
||||
private _unpackers: Record<string, Unpacker> = {
|
||||
private _loading$ = new Cache<IUnpackRequest[]>();
|
||||
private _unpackers$: Record<string, Unpacker> = {
|
||||
'.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<string, Unpacker>): void;
|
||||
public register (type: string | Record<string, Unpacker>, 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];
|
||||
|
||||
@@ -43,9 +43,9 @@ export type ParseHandler = (file: any, options: Record<string, any>, 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<string, ParseHandler> = {
|
||||
private _parsers$: Record<string, ParseHandler> = {
|
||||
'.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;
|
||||
}
|
||||
|
||||
@@ -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<string, any> {
|
||||
private _parseDict$ (node: HTMLElement): Record<string, any> {
|
||||
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;
|
||||
|
||||
@@ -113,18 +113,18 @@ function checkCircularReference (asset: Asset): number {
|
||||
}
|
||||
|
||||
class ReleaseManager {
|
||||
private _persistNodeDeps = new Cache<string[]>();
|
||||
private _toDelete = new Cache<Asset>();
|
||||
private _eventListener = false;
|
||||
private _dontDestroyAssets: string[] = [];
|
||||
private _persistNodeDeps$ = new Cache<string[]>();
|
||||
private _toDelete$ = new Cache<Asset>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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$);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 _flatBuffers$: IFlatBuffer[] = [];
|
||||
|
||||
private _jointMappedBuffers?: Buffer[];
|
||||
private _jointMappedBuffers$?: Buffer[];
|
||||
|
||||
private _jointMappedBufferIndices?: number[];
|
||||
private _jointMappedBufferIndices$?: number[];
|
||||
|
||||
private _vertexIdChannel?: { stream: number; index: number };
|
||||
private _vertexIdChannel$?: { stream: number; index: number };
|
||||
|
||||
private _geometricInfo?: IGeometricInfo;
|
||||
private _geometricInfo$?: IGeometricInfo;
|
||||
|
||||
private _vertexBuffers: Buffer[];
|
||||
private _vertexBuffers$: Buffer[];
|
||||
|
||||
private declare _attributes: Attribute[];
|
||||
private declare _attributes$: Attribute[];
|
||||
|
||||
private declare _indexBuffer: Buffer | null;
|
||||
private declare _indexBuffer$: Buffer | null;
|
||||
|
||||
private declare _indirectBuffer: Buffer | null;
|
||||
private declare _indirectBuffer$: Buffer | null;
|
||||
|
||||
private declare _primitiveMode: PrimitiveMode;
|
||||
private declare _primitiveMode$: PrimitiveMode;
|
||||
|
||||
private declare _iaInfo: InputAssemblerInfo;
|
||||
private declare _iaInfo$: InputAssemblerInfo;
|
||||
|
||||
private declare _isOwnerOfIndexBuffer: boolean;
|
||||
private declare _isOwnerOfIndexBuffer$: boolean;
|
||||
|
||||
private _drawInfo?: DrawInfo | null = null;
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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<SamplerInfo> {
|
||||
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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -343,7 +343,7 @@ export class QuatCurve extends KeyframeCurve<QuatKeyframeValue> {
|
||||
|
||||
// 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<QuatKeyframeValue> {
|
||||
|
||||
// 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<QuatKeyframeValue> {
|
||||
}
|
||||
}
|
||||
|
||||
enum KeyframeValueFlagMask {
|
||||
enum QuatCurveKeyframeValueFlagMask {
|
||||
INTERPOLATION_MODE = 1 << 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -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<any, GCObject> = new WeakMap();
|
||||
private _finalizationRegistry$: FinalizationRegistry | null = EDITOR && typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry(this.finalizationRegistryCallback$.bind(this)) : null;
|
||||
private _gcObjects$: WeakMap<any, GCObject> = 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 {
|
||||
|
||||
@@ -26,6 +26,7 @@ import { garbageCollectionManager } from './garbage-collection';
|
||||
*/
|
||||
export class GCObject {
|
||||
constructor () {
|
||||
// eslint-disable-next-line no-constructor-return
|
||||
return garbageCollectionManager.registerGCObject(this);
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ import { array } from '../utils/js';
|
||||
* ```
|
||||
*/
|
||||
export class AsyncDelegate<T extends (...args: any) => (Promise<void> | void) = () => (Promise<void> | void)> {
|
||||
private _delegates: T[] = [];
|
||||
private _delegates$: T[] = [];
|
||||
|
||||
/**
|
||||
* @en
|
||||
@@ -61,8 +61,8 @@ export class AsyncDelegate<T extends (...args: any) => (Promise<void> | 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<T extends (...args: any) => (Promise<void> | 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<T extends (...args: any) => (Promise<void> | 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<T extends (...args: any) => (Promise<void> | void) =
|
||||
* @returns @en The promise awaiting all async callback resolved. @zh 等待所有异步回调结束的 Promise 对象。
|
||||
*/
|
||||
public dispatch (...args: Parameters<T>): Promise<void[]> {
|
||||
return Promise.all(this._delegates.map((func) => func(...arguments)).filter(Boolean));
|
||||
return Promise.all(this._delegates$.map((func) => func(...arguments)).filter(Boolean));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ export class CallbacksInvoker<EventTypeClass extends EventType = EventType> {
|
||||
* @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<EventTypeClass extends EventType = EventType> {
|
||||
this.removeAll(key);
|
||||
}
|
||||
}
|
||||
this._offCallback?.();
|
||||
this._offCallback$?.();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -375,7 +375,7 @@ export class CallbacksInvoker<EventTypeClass extends EventType = EventType> {
|
||||
* @engineInternal
|
||||
*/
|
||||
public _registerOffCallback (cb: () => void): void {
|
||||
this._offCallback = cb;
|
||||
this._offCallback$ = cb;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Vec3>(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);
|
||||
|
||||
@@ -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<Vec3>(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<Vec3>(8);
|
||||
const vertices2 = new Array<Vec3>(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<Vec3>(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<Vec3>(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<Vec3>(8);
|
||||
const vertices2 = new Array<Vec3>(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[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[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[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[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[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[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[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[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[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[enums.SHAPE_CAPSULE] = capsuleWithCapsule;
|
||||
intersect[ShapeType.SHAPE_CAPSULE] = capsuleWithCapsule;
|
||||
|
||||
export default intersect;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+68
-24
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Vec3[]> = []) {
|
||||
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<Vec3[]> {
|
||||
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<Vec3> {
|
||||
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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
+111
-175
@@ -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 <Out extends IMat3Like> (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;
|
||||
|
||||
this.m01 = yx + wz;
|
||||
this.m04 = 1 - xx - zz;
|
||||
this.m07 = zy - wx;
|
||||
self.m00 = 1 - yy - zz;
|
||||
self.m03 = yx - wz;
|
||||
self.m06 = zx + wy;
|
||||
|
||||
this.m02 = zx - wy;
|
||||
this.m05 = zy + wx;
|
||||
this.m08 = 1 - xx - yy;
|
||||
return this;
|
||||
self.m01 = yx + wz;
|
||||
self.m04 = 1 - xx - zz;
|
||||
self.m07 = zy - wx;
|
||||
|
||||
self.m02 = zx - wy;
|
||||
self.m05 = zy + wx;
|
||||
self.m08 = 1 - xx - yy;
|
||||
return self;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+337
-535
File diff suppressed because it is too large
Load Diff
@@ -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,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
for (const staticKey of ['__attrs__', '__props__', '__values__']) {
|
||||
ctor[staticKey] = parentCtor[staticKey];
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
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];
|
||||
}
|
||||
};
|
||||
|
||||
extendType(jsb.Mat4.prototype, Mat4.prototype, MathType.MAT4);
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
|
||||
+69
-54
@@ -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<Out extends IQuatLike, VecLike extends IVec3Like> (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 extends IQuatLike> (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 extends IQuatLike> (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 extends IQuatLike> (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<Out extends IQuatLike> (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 extends IQuatLike> (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 extends IQuatLike, VecLike extends IVec3Like> (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 extends IQuatLike> (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;
|
||||
|
||||
+76
-63
@@ -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 extends IRectLike, VecLike extends IVec2Like> (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;
|
||||
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 this;
|
||||
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;
|
||||
|
||||
+54
-48
@@ -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 extends IVec2Like> (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 extends IVec2Like> (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 extends IVec2Like> (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 extends IVec2Like> (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 extends IVec2Like> (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 <Out extends IVec2Like> (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 <Out extends IVec2Like> (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 extends IVec2Like> (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 <Out extends IVec2Like> (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;
|
||||
}
|
||||
|
||||
|
||||
+95
-85
@@ -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 extends IVec3Like> (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 extends IVec3Like> (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 extends IVec3Like> (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 extends IVec3Like> (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 extends IVec3Like> (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 extends IVec3Like> (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<Vec3>, axis: Readonly<V
|
||||
// Here we duplicate the code to avoid circular reference.
|
||||
|
||||
const rad = angle * 0.5;
|
||||
const s = Math.sin(rad);
|
||||
const s = sin(rad);
|
||||
cacheQ.x = s * axis.x;
|
||||
cacheQ.y = s * axis.y;
|
||||
cacheQ.z = s * axis.z;
|
||||
cacheQ.w = Math.cos(rad);
|
||||
cacheQ.w = cos(rad);
|
||||
|
||||
Vec3.transformQuat(out, input, cacheQ);
|
||||
return out;
|
||||
|
||||
+190
-156
@@ -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.
|
||||
@@ -29,7 +30,18 @@ import { Mat4 } from './mat4';
|
||||
import { IMat4Like, IQuatLike, IVec4Like, IColorLike } from './type-define';
|
||||
import { clamp, EPSILON, 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 sin = Math.sin;
|
||||
const cos = Math.cos;
|
||||
const atan2 = Math.atan2;
|
||||
const sqrt = Math.sqrt;
|
||||
const ceil = Math.ceil;
|
||||
const floor = Math.floor;
|
||||
const round = Math.round;
|
||||
|
||||
/**
|
||||
* @en Representation of four-dimensional vectors.
|
||||
@@ -101,7 +113,7 @@ export class Vec4 extends ValueType {
|
||||
const dz = (a.x * b.y - a.y * b.x);
|
||||
|
||||
const dotVal = (a.x * b.x + a.y * b.y + a.z * b.z);
|
||||
return Math.atan2(Math.sqrt(dx * dx + dy * dy + dz * dz), dotVal);
|
||||
return atan2(sqrt(dx * dx + dy * dy + dz * dz), dotVal);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -157,10 +169,10 @@ export class Vec4 extends ValueType {
|
||||
* @zh 逐元素向量向上取整
|
||||
*/
|
||||
public static ceil <Out extends IVec4Like> (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 extends IVec4Like> (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 extends IVec4Like> (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 extends IVec4Like> (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 extends IVec4Like> (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 extends IVec4Like> (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 <Out extends IVec4Like> (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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,8 +49,8 @@ export class CachedArray<T> 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<T> 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<T> 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<T> extends ScalableContainer {
|
||||
*/
|
||||
public sort (): void {
|
||||
this.array.length = this.length;
|
||||
this.array.sort(this._compareFn);
|
||||
this.array.sort(this._compareFn$);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+37
-37
@@ -33,12 +33,12 @@ import { ScalableContainer } from './scalable-container';
|
||||
* @see [[RecyclePool]]
|
||||
*/
|
||||
export class Pool<T> 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<T> 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;
|
||||
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());
|
||||
for (let i = 0; i < this._elementsPerBatch$; ++i) {
|
||||
this._freePool$.push(ctor());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,15 +76,15 @@ export class Pool<T> 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<T> 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<T> 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<T> 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<T> 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,9 +38,9 @@ import { ScalableContainer } from './scalable-container';
|
||||
export class RecyclePool<T = any> 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<T = any> 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<T = any> extends ScalableContainer {
|
||||
* @zh 对象池大小。
|
||||
*/
|
||||
get length (): number {
|
||||
return this._count;
|
||||
return this._count$;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,7 +74,7 @@ export class RecyclePool<T = any> extends ScalableContainer {
|
||||
* @zh 实际对象池数组。
|
||||
*/
|
||||
get data (): T[] {
|
||||
return this._data;
|
||||
return this._data$;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,7 +82,7 @@ export class RecyclePool<T = any> extends ScalableContainer {
|
||||
* @zh 清空对象池。目前仅仅会设置尺寸为 0。
|
||||
*/
|
||||
public reset (): void {
|
||||
this._count = 0;
|
||||
this._count$ = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,9 +91,9 @@ export class RecyclePool<T = any> 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<T = any> 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<T = any> 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<T = any> 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<T = any> 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+298
-298
File diff suppressed because it is too large
Load Diff
+22
-22
@@ -34,7 +34,7 @@ declare const require: (path: string) => Promise<void>;
|
||||
* @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<T = any> (category: Category | string, name: string, value: T): void {
|
||||
if (!(category in this._override)) {
|
||||
this._override[category] = {};
|
||||
overrideSettings<T = any> (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<T = any> (category: Category | string, name: string): T | null {
|
||||
if (category in this._override) {
|
||||
const categorySettings = this._override[category];
|
||||
querySettings<T = any> (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<string, any> = {};
|
||||
private _override: Record<string, any> = {};
|
||||
private _settings$: Record<string, any> = {};
|
||||
private _override$: Record<string, any> = {};
|
||||
}
|
||||
|
||||
export declare namespace Settings {
|
||||
export type Category = typeof Category;
|
||||
export type Category = typeof SettingsCategory;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -98,8 +98,8 @@ export class Pool<T> {
|
||||
return this._get();
|
||||
}
|
||||
|
||||
private declare _pool: Array<T | null>;
|
||||
private declare _cleanup: CleanUpFunction<T> | null;
|
||||
private declare _pool$: Array<T | null>;
|
||||
private declare _cleanup$: CleanUpFunction<T> | null;
|
||||
|
||||
/**
|
||||
* @en Constructor. @zh 构造函数。
|
||||
@@ -125,8 +125,8 @@ export class Pool<T> {
|
||||
constructor (_0: CleanUpFunction<T> | number, _1?: number) {
|
||||
const size = (_1 === undefined) ? (_0 as number) : _1;
|
||||
const cleanupFunc = (_1 === undefined) ? null : (_0 as CleanUpFunction<T>);
|
||||
this._pool = new Array(size);
|
||||
this._cleanup = cleanupFunc;
|
||||
this._pool$ = new Array(size);
|
||||
this._cleanup$ = cleanupFunc;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -140,8 +140,8 @@ export class Pool<T> {
|
||||
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<T> {
|
||||
* @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<T> {
|
||||
*/
|
||||
public resize (length: number): void {
|
||||
if (length >= 0) {
|
||||
this._pool.length = length;
|
||||
this._pool$.length = length;
|
||||
if (this.count > length) {
|
||||
this.count = length;
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ ccenum(DefaultAnimsEnum);
|
||||
enum DefaultCacheMode {
|
||||
REALTIME = 0,
|
||||
}
|
||||
ccenum(DefaultAnimsEnum);
|
||||
ccenum(DefaultCacheMode);
|
||||
|
||||
/**
|
||||
* @en Control animation speed, should be larger than 0.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 动画帧相关的事件。
|
||||
|
||||
+214
-100
@@ -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.<br/>
|
||||
* @zh 物理过程之前所触发的事件。
|
||||
* @event BEFORE_PHYSICS
|
||||
*/
|
||||
BEFORE_PHYSICS = 'director_before_physics',
|
||||
|
||||
/**
|
||||
* @en The event which will be triggered after the physics process.<br/>
|
||||
* @zh 物理过程之后所触发的事件。
|
||||
* @event AFTER_PHYSICS
|
||||
*/
|
||||
AFTER_PHYSICS = 'director_after_physics',
|
||||
|
||||
/**
|
||||
* @en The event which will be triggered at the frame begin.<br/>
|
||||
* @zh 一帧开始时所触发的事件。
|
||||
* @event BEGIN_FRAME
|
||||
*/
|
||||
BEGIN_FRAME = 'director_begin_frame',
|
||||
|
||||
/**
|
||||
* @en The event which will be triggered at the frame end.<br/>
|
||||
* @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.<br/>
|
||||
* @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.<br/>
|
||||
* @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.<br/>
|
||||
* @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.<br/>
|
||||
* @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<string, Node> = {};
|
||||
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<string, Node> = {};
|
||||
|
||||
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);
|
||||
|
||||
+132
-116
@@ -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<void> {
|
||||
const endFramePromise = new Promise<void>((resolve): void => { director.once(Director.EVENT_END_FRAME, (): void => resolve()); });
|
||||
const endFramePromise = new Promise<void>((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<void[]> => {
|
||||
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<void> {
|
||||
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<void> => sys.init())
|
||||
.then((): void => {
|
||||
this._initEvents();
|
||||
this._initEvents$();
|
||||
})
|
||||
.then((): Promise<void> => settings.init(config.settingsPath, config.overrideSettings))
|
||||
.then((): Promise<void[]> => {
|
||||
@@ -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<void> => effectSettings.init(settings.querySettings(Settings.Category.RENDERING, 'effectSettingsPath') as string))
|
||||
.then((): Promise<void> => 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<any[]> => {
|
||||
const scriptPackages = settings.querySettings<string[]>(Settings.Category.SCRIPTING, 'scriptPackages');
|
||||
const scriptPackages = settings.querySettings<string[]>(SettingsCategory.SCRIPTING, 'scriptPackages');
|
||||
if (scriptPackages) {
|
||||
return Promise.all(scriptPackages.map((pack): Promise<any> => 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<string[]>(Settings.Category.PLUGINS, 'jsList');
|
||||
const jsList = settings.querySettings<string[]>(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<any[]> => this._loadProjectBundles())
|
||||
.then((): Promise<void> => this._loadCCEScripts())
|
||||
.then((): void | Promise<void> => this._setupRenderPipeline())
|
||||
.then((): Promise<any[]> => this._loadPreloadAssets())
|
||||
.then((): Promise<void> => this._loadCCEScripts$())
|
||||
.then((): void | Promise<void> => this._setupRenderPipeline$())
|
||||
.then((): Promise<any[]> => this._loadPreloadAssets$())
|
||||
.then((): Promise<void[]> => {
|
||||
builtinResMgr.compileBuiltinMaterial();
|
||||
return SplashScreen.instance.init();
|
||||
if (WECHAT) {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
return SplashScreen.createInstance().init();
|
||||
})
|
||||
.then((): Promise<void[]> => {
|
||||
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<any[]> {
|
||||
const preloadAssets = settings.querySettings<string[]>(Settings.Category.ASSETS, 'preloadAssets');
|
||||
private _loadPreloadAssets$ (): Promise<any[]> {
|
||||
const preloadAssets = settings.querySettings<string[]>(SettingsCategory.ASSETS, 'preloadAssets');
|
||||
if (!preloadAssets) return Promise.resolve([]);
|
||||
return Promise.all(preloadAssets.map((uuid): Promise<void> => new Promise<void>((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<void> {
|
||||
private _loadCCEScripts$ (): Promise<void> {
|
||||
return new Promise<void>((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<void[]> {
|
||||
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<void> => new Promise<void>((resolve, reject): void => {
|
||||
const opts: Record<string, any> = {};
|
||||
@@ -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<void> {
|
||||
private _setupRenderPipeline$ (): void | Promise<void> {
|
||||
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);
|
||||
|
||||
+312
-309
@@ -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 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 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 bgMat$!: Material;
|
||||
private bgImage$!: HTMLImageElement;
|
||||
private bgTexture$!: Texture;
|
||||
|
||||
private logoMat!: Material;
|
||||
private logoImage!: HTMLImageElement;
|
||||
private logoTexture!: Texture;
|
||||
private logoMat$!: Material;
|
||||
private logoImage$!: HTMLImageElement;
|
||||
private logoTexture$!: Texture;
|
||||
|
||||
private watermarkMat!: Material;
|
||||
private watermarkTexture!: 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 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 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 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<void[]> {
|
||||
// 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<number>(Settings.Category.SPLASH_SCREEN, 'displayRatio') ?? 0.4,
|
||||
totalTime: settings.querySettings<number>(Settings.Category.SPLASH_SCREEN, 'totalTime') ?? 3000,
|
||||
watermarkLocation: settings.querySettings<WatermarkLocationType>(Settings.Category.SPLASH_SCREEN, 'watermarkLocation') ?? 'default',
|
||||
autoFit: settings.querySettings<boolean>(Settings.Category.SPLASH_SCREEN, 'autoFit') ?? true,
|
||||
logo: settings.querySettings<SplashLogo>(Settings.Category.SPLASH_SCREEN, 'logo') ?? undefined,
|
||||
background: settings.querySettings<SplashBackground>(Settings.Category.SPLASH_SCREEN, 'background') ?? undefined,
|
||||
displayRatio: settings.querySettings<number>(SettingsCategory.SPLASH_SCREEN, 'displayRatio') ?? 0.4,
|
||||
totalTime: settings.querySettings<number>(SettingsCategory.SPLASH_SCREEN, 'totalTime') ?? 3000,
|
||||
watermarkLocation: settings.querySettings<WatermarkLocationType>(SettingsCategory.SPLASH_SCREEN, 'watermarkLocation') ?? 'default',
|
||||
autoFit: settings.querySettings<boolean>(SettingsCategory.SPLASH_SCREEN, 'autoFit') ?? true,
|
||||
logo: settings.querySettings<SplashLogo>(SettingsCategory.SPLASH_SCREEN, 'logo') ?? undefined,
|
||||
background: settings.querySettings<SplashBackground>(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<void>((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<void>((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!;
|
||||
}
|
||||
|
||||
this.settings = null!;
|
||||
if (this.watermarkTexture$) {
|
||||
this.watermarkTexture$.destroy();
|
||||
this.watermarkTexture$ = 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 () {}
|
||||
}
|
||||
|
||||
+150
-150
@@ -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 _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 _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 _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 _needSimulateTouchMoveEvent$ = false;
|
||||
|
||||
private declare _inputEventDispatcher: InputEventDispatcher;
|
||||
private _eventDispatcherList: IEventDispatcher[] = [];
|
||||
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<K extends keyof InputEventMap> (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<K extends keyof InputEventMap> (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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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$;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+36
-36
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<typeof ISO>;
|
||||
}
|
||||
|
||||
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')
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<boolean>(Settings.Category.PHYSICS, 'allowSleep') ?? this._allowSleep;
|
||||
this._fixedTimeStep = settings.querySettings<number>(Settings.Category.PHYSICS, 'fixedTimeStep') ?? this._fixedTimeStep;
|
||||
this._maxSubSteps = settings.querySettings<number>(Settings.Category.PHYSICS, 'maxSubSteps') ?? this._maxSubSteps;
|
||||
this._autoSimulation = settings.querySettings<boolean>(Settings.Category.PHYSICS, 'autoSimulation') ?? this._autoSimulation;
|
||||
const collisionMatrix = settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix');
|
||||
this._allowSleep = settings.querySettings<boolean>(SettingsCategory.PHYSICS, 'allowSleep') ?? this._allowSleep;
|
||||
this._fixedTimeStep = settings.querySettings<number>(SettingsCategory.PHYSICS, 'fixedTimeStep') ?? this._fixedTimeStep;
|
||||
this._maxSubSteps = settings.querySettings<number>(SettingsCategory.PHYSICS, 'maxSubSteps') ?? this._maxSubSteps;
|
||||
this._autoSimulation = settings.querySettings<boolean>(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<Array<{ name: string, index: number }>>(Settings.Category.PHYSICS, 'collisionGroups');
|
||||
const collisionGroups = settings.querySettings<Array<{ name: string, index: number }>>(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(); });
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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';
|
||||
@@ -227,7 +227,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();
|
||||
@@ -360,7 +360,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();
|
||||
@@ -374,7 +374,7 @@ export class PhysicsSystem extends System implements IWorldInitData {
|
||||
break;
|
||||
}
|
||||
}
|
||||
director.emit(Director.EVENT_AFTER_PHYSICS);
|
||||
director.emit(DirectorEvent.AFTER_PHYSICS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,27 +385,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<Array<{ name: string, index: number }>>(Settings.Category.PHYSICS, 'collisionGroups');
|
||||
const collisionGroups = config ? config.collisionGroups : settings.querySettings<Array<{ name: string, index: number }>>(SettingsCategory.PHYSICS, 'collisionGroups');
|
||||
if (collisionGroups) {
|
||||
const cg = collisionGroups;
|
||||
if (cg instanceof Array) {
|
||||
@@ -866,7 +866,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
|
||||
@@ -885,4 +885,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(); });
|
||||
|
||||
+17
-17
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -65,90 +65,90 @@ class BufferPool<P extends PoolType, E extends BufferManifest> implements IMemor
|
||||
// naming convension:
|
||||
// this._bufferViews[chunk][entry][element]
|
||||
|
||||
private declare _dataType: BufferDataTypeManifest<E>;
|
||||
private declare _dataMembers: BufferDataMembersManifest<E>;
|
||||
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<E>;
|
||||
private declare _dataMembers$: BufferDataMembersManifest<E>;
|
||||
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<E>, dataMembers: BufferDataMembersManifest<E>, 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<P> {
|
||||
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<P>;
|
||||
return (i << this._entryBits$) + j + this._poolFlag$ as unknown as IHandle<P>;
|
||||
}
|
||||
}
|
||||
// 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<P>;
|
||||
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<P>;
|
||||
return handle; // guarantees the handle is always not zero
|
||||
}
|
||||
|
||||
public getBuffer (handle: IHandle<P>): 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<P extends PoolType, E extends BufferManifest> implements IMemor
|
||||
}
|
||||
|
||||
public getTypedArray<K extends E[keyof E]> (handle: IHandle<P>, 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<P>): 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user