From 32598c25cb62d0f915b81603246a2eb37bcf7719 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 9 Nov 2020 10:19:12 +0800 Subject: [PATCH] switch to eslint (#7727) * switch to eslint * eslint: extends airbnb --- .editorconfig | 2 +- .eslintrc.json | 173 -- .eslintrc.yaml | 104 + .jshintrc | 42 - .vscode/settings.json | 5 +- @types/globals.d.ts | 5 +- cocos/audio/assets/clip.ts | 14 +- cocos/audio/assets/player.ts | 13 +- cocos/audio/audio-downloader.ts | 11 +- cocos/audio/audio-utils.ts | 11 +- cocos/core/3d/builtin/effects.ts | 2 +- cocos/core/3d/builtin/shader-sources/glsl1.ts | 2 +- cocos/core/3d/builtin/shader-sources/glsl3.ts | 2 +- cocos/core/3d/builtin/shader-sources/glsl4.ts | 2 +- cocos/core/3d/framework/camera-component.ts | 4 +- cocos/core/3d/framework/light-component.ts | 4 +- cocos/core/3d/framework/mesh-renderer.ts | 4 +- .../core/3d/framework/renderable-component.ts | 16 +- .../framework/skinned-mesh-batch-renderer.ts | 42 +- .../3d/framework/skinned-mesh-renderer.ts | 5 +- .../core/3d/framework/spot-light-component.ts | 15 +- cocos/core/animation/animation-component.ts | 2 +- cocos/core/animation/animation-curve.ts | 2 +- cocos/core/animation/cubic-spline-value.ts | 2 +- cocos/core/animation/motion-path-helper.ts | 10 +- .../animation/skeletal-animation-data-hub.ts | 18 +- .../animation/skeletal-animation-state.ts | 14 +- cocos/core/animation/skeletal-animation.ts | 23 +- cocos/core/asset-manager/asset-manager.ts | 10 +- cocos/core/asset-manager/bundle.ts | 2 +- cocos/core/asset-manager/depend-util.ts | 10 +- cocos/core/asset-manager/deprecated.ts | 6 +- cocos/core/asset-manager/factory.ts | 89 +- cocos/core/asset-manager/fetch.ts | 2 +- cocos/core/asset-manager/font-loader.ts | 4 +- cocos/core/asset-manager/load.ts | 6 +- cocos/core/asset-manager/pack-manager.ts | 2 +- cocos/core/asset-manager/release-manager.ts | 8 +- cocos/core/asset-manager/utilities.ts | 10 +- cocos/core/assets/asset.ts | 2 +- cocos/core/assets/deprecation.ts | 2 +- cocos/core/assets/label-atlas.ts | 2 +- cocos/core/assets/material.ts | 68 +- cocos/core/assets/mesh.ts | 375 +-- cocos/core/assets/prefab.ts | 10 +- cocos/core/assets/render-texture.ts | 2 +- cocos/core/assets/sprite-frame.ts | 2 +- cocos/core/components/component.ts | 53 +- cocos/core/components/missing-script.ts | 2 +- cocos/core/components/ui-base/ui-transform.ts | 10 +- cocos/core/data/class.ts | 15 +- cocos/core/data/deserialize-dynamic.ts | 22 +- cocos/core/data/deserialize.ts | 34 +- cocos/core/data/instantiate-jit.ts | 12 +- cocos/core/data/instantiate.ts | 10 +- cocos/core/data/object.ts | 20 +- cocos/core/data/utils/attribute.ts | 4 +- cocos/core/data/utils/preprocess-class.ts | 6 +- cocos/core/data/utils/requiring-frame.ts | 2 +- cocos/core/default-constants.ts | 4 +- cocos/core/director.ts | 11 +- cocos/core/event/event-target-factory.ts | 2 +- cocos/core/event/event-target.ts | 3 +- cocos/core/game.ts | 50 +- cocos/core/geometry/aabb.ts | 2 +- cocos/core/geometry/frustum.ts | 2 +- cocos/core/geometry/intersect.ts | 12 +- cocos/core/geometry/line.ts | 2 +- cocos/core/geometry/obb.ts | 2 +- cocos/core/geometry/plane.ts | 2 +- cocos/core/geometry/ray.ts | 8 +- cocos/core/geometry/sphere.ts | 4 +- cocos/core/geometry/triangle.ts | 14 +- cocos/core/gfx/buffer.ts | 18 +- cocos/core/gfx/command-buffer.ts | 25 +- cocos/core/gfx/define-class.ts | 16 +- cocos/core/gfx/define.ts | 4 +- cocos/core/gfx/descriptor-set-layout.ts | 6 +- cocos/core/gfx/descriptor-set.ts | 12 +- cocos/core/gfx/device.ts | 72 +- cocos/core/gfx/fence.ts | 6 +- cocos/core/gfx/framebuffer.ts | 4 +- cocos/core/gfx/index.ts | 2 +- cocos/core/gfx/input-assembler.ts | 30 +- cocos/core/gfx/pipeline-layout.ts | 6 +- cocos/core/gfx/pipeline-state.jsb.ts | 20 +- cocos/core/gfx/pipeline-state.ts | 37 +- cocos/core/gfx/polyfill-legacy-cc.ts | 32 +- cocos/core/gfx/queue.ts | 8 +- cocos/core/gfx/render-pass.ts | 24 +- cocos/core/gfx/sampler.ts | 12 +- cocos/core/gfx/shader.ts | 18 +- cocos/core/gfx/texture.ts | 22 +- cocos/core/gfx/webgl/webgl-command-buffer.ts | 6 +- cocos/core/gfx/webgl/webgl-commands.ts | 2353 ++++++++-------- cocos/core/gfx/webgl/webgl-device.ts | 2 +- cocos/core/gfx/webgl2/webgl2-commands.ts | 2416 ++++++++--------- cocos/core/global-exports.ts | 1 - cocos/core/math/color.ts | 8 +- cocos/core/math/mat3.ts | 14 +- cocos/core/math/mat4.ts | 2 +- cocos/core/memop/sort.ts | 2 +- cocos/core/pipeline/define.ts | 10 +- .../pipeline/render-additive-light-queue.ts | 185 +- cocos/core/platform/debug.ts | 4 +- .../platform/event-manager/event-manager.ts | 18 +- cocos/core/platform/event-manager/events.ts | 8 +- .../platform/event-manager/input-manager.ts | 37 +- cocos/core/platform/sys.ts | 45 +- cocos/core/platform/view.ts | 45 +- cocos/core/renderer/core/material-instance.ts | 2 +- cocos/core/renderer/core/memory-pools.ts | 444 +-- cocos/core/renderer/core/pass-instance.ts | 3 +- cocos/core/renderer/core/pass-utils.ts | 64 +- cocos/core/renderer/core/pass.ts | 249 +- cocos/core/renderer/core/program-lib.ts | 10 +- cocos/core/renderer/core/render-window.ts | 10 +- .../core/renderer/core/texture-buffer-pool.ts | 2 +- .../renderer/models/baked-skinning-model.ts | 2 +- .../models/skeletal-animation-utils.ts | 64 +- cocos/core/renderer/models/skinning-model.ts | 4 +- cocos/core/renderer/scene/light.ts | 29 +- cocos/core/renderer/scene/model.ts | 6 +- cocos/core/renderer/scene/skybox.ts | 2 +- cocos/core/renderer/scene/spot-light.ts | 21 +- cocos/core/renderer/scene/submodel.ts | 32 +- cocos/core/root.ts | 12 +- cocos/core/scene-graph/base-node-dev.ts | 6 +- cocos/core/scene-graph/base-node.ts | 21 +- cocos/core/scene-graph/component-scheduler.ts | 19 +- cocos/core/scene-graph/layers.ts | 77 +- cocos/core/scene-graph/node-activator.ts | 18 +- cocos/core/scene-graph/node.ts | 151 +- cocos/core/scene-graph/private-node.ts | 5 +- cocos/core/scene-graph/scene.ts | 27 +- cocos/core/scheduler.ts | 108 +- cocos/core/utils/array.ts | 1 - cocos/core/utils/binary-search.ts | 2 +- cocos/core/utils/misc.ts | 12 +- cocos/core/utils/prefab-helper.ts | 3 - cocos/core/utils/profiler/profiler.ts | 4 +- cocos/core/value-types/bitmask.ts | 4 +- cocos/core/value-types/enum.ts | 14 +- cocos/particle/animator/color-overtime.ts | 2 +- cocos/particle/animator/force-overtime.ts | 2 +- cocos/particle/animator/gradient-range.ts | 4 +- cocos/particle/animator/gradient.ts | 2 +- .../animator/limit-velocity-overtime.ts | 2 +- cocos/particle/animator/optimized-curve.ts | 2 +- cocos/particle/animator/rotation-overtime.ts | 2 +- cocos/particle/animator/size-overtime.ts | 2 +- cocos/particle/animator/texture-animation.ts | 4 +- cocos/particle/animator/velocity-overtime.ts | 2 +- cocos/particle/line.ts | 16 +- cocos/particle/particle-system.ts | 72 +- cocos/particle/renderer/trail.ts | 24 +- cocos/physics/cocos/builtin-shared-body.ts | 8 +- cocos/terrain/terrain.ts | 38 +- cocos/tiledmap/tiled-map.ts | 28 +- cocos/ui/assembler/label/ttf.ts | 2 +- cocos/ui/components/mask.ts | 20 +- cocos/ui/components/page-view.ts | 81 +- cocos/ui/components/rich-text.ts | 67 +- cocos/ui/components/safe-area.ts | 25 +- cocos/ui/components/sprite.ts | 15 +- cocos/ui/components/ui-mesh-renderer.ts | 2 +- cocos/ui/components/widget-manager.ts | 15 +- cocos/ui/components/widget.ts | 69 +- editor/exports/offline-mappings.ts | 2 +- package-lock.json | 1407 ++++++++-- package.json | 8 +- tslint.json | 35 - 172 files changed, 5698 insertions(+), 4687 deletions(-) delete mode 100644 .eslintrc.json create mode 100644 .eslintrc.yaml delete mode 100644 .jshintrc delete mode 100644 tslint.json diff --git a/.editorconfig b/.editorconfig index 365f9971ec..40dbc3fe0d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,4 +9,4 @@ end_of_line = lf indent_size = 4 indent_style = space insert_final_newline = true -trim_trailing_whitespace = true \ No newline at end of file +trim_trailing_whitespace = true diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index a741540142..0000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,173 +0,0 @@ -{ - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": "./tsconfig.json" - }, - "extends": "plugin:@typescript-eslint/recommended", - "plugins": [ - "@typescript-eslint" - ], - "settings": { - "import/resolver": { - "node": { - "extensions": [ - ".js", - ".jsx", - ".ts", - ".tsx", - ".d.ts" - ] - } - } - }, - "rules": { - "quotes": "off",//["warn", "single"], - "no-console": "warn", - "space-before-function-paren": "warn", - "max-len": [ - "warn", - 160 - ], - - "camelcase": "off", - "indent": "off", - "no-empty-function": "off", - "no-extra-parens": "off", - "semi": "off", - - "sort-imports": ["warn", { - "memberSyntaxSortOrder": ["all", "single", "multiple", "none"] - }], - - "@typescript-eslint/adjacent-overload-signatures": "off", - "@typescript-eslint/array-type": ["warn", { - "default": "array" - }], - "@typescript-eslint/await-thenable": "off", - "@typescript-eslint/ban-ts-ignore": "warn", - "@typescript-eslint/ban-types": ["warn", { - "types": { - "Object": "Use {} instead" - } - }], - "@typescript-eslint/camelcase": ["error", { - "allow": [ - "^_[a-z]", - "^[a-zA-Z]" - ] - }], - "@typescript-eslint/class-name-casing": "warn", - "@typescript-eslint/consistent-type-definitions": "off", - "@typescript-eslint/explicit-function-return-type": "off", - "@typescript-eslint/explicit-member-accessibility": ["warn", { - "accessibility": "explicit", - "overrides": { - "constructors": "off", - "accessors": "off" - } - }], - "@typescript-eslint/func-call-spacing": "warn", - "@typescript-eslint/generic-type-naming": "off", - "@typescript-eslint/indent": ["warn", 4], - "@typescript-eslint/interface-name-prefix": "off",//["warn", "never"], - "@typescript-eslint/member-delimiter-style": ["warn", { - "multiline": { - "delimiter": "semi", - "requireLast": true - }, - "singleline": { - "delimiter": "semi" - } - }], - "@typescript-eslint/member-naming": ["warn", { - "private": "^_" - }], - "@typescript-eslint/member-ordering": ["warn", { - "default": [ - "public-static-field", - "protected-static-field", - "private-static-field", - "static-field", - "public-instance-field", - "protected-instance-field", - "private-instance-field", - "public-field", - "protected-field", - "private-field", - "instance-field", - "field", - "constructor", - "public-static-method", - "protected-static-method", - "private-static-method", - "static-method", - "public-instance-method", - "protected-instance-method", - "private-instance-method", - "public-method", - "protected-method", - "private-method", - "instance-method", - "method" - ] - }], - "@typescript-eslint/no-array-constructor": ["error"], - "@typescript-eslint/no-empty-function": "off", - "@typescript-eslint/no-empty-interface": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-extra-parens": "off", - "@typescript-eslint/no-extraneous-class": "warn", - "@typescript-eslint/no-floating-promises": "off", - "@typescript-eslint/no-for-in-array": "warn", - "@typescript-eslint/no-inferrable-types": "off", - "@typescript-eslint/no-magic-numbers": ["off", { - "ignoreNumericLiteralTypes": true, - "ignoreEnums": true - }], - "@typescript-eslint/no-misused-new": "error", - "@typescript-eslint/no-misused-promises": "error", - "@typescript-eslint/no-namespace": "off", - "@typescript-eslint/no-non-null-assertion": "warn", - "@typescript-eslint/no-parameter-properties": "off", - "@typescript-eslint/no-require-imports": "error", - "@typescript-eslint/no-this-alias": "warn", - "@typescript-eslint/no-type-alias": "off", - "@typescript-eslint/no-unnecessary-qualifier": "off", - "@typescript-eslint/no-unnecessary-type-assertion": "warn", - "@typescript-eslint/no-unused-vars": "off", - "@typescript-eslint/no-use-before-define": "off", - "@typescript-eslint/no-useless-constructor": "off", - "@typescript-eslint/no-var-requires": "error", - "@typescript-eslint/prefer-for-of": "off", - "@typescript-eslint/prefer-function-type": "off", - "@typescript-eslint/prefer-includes": "warn", - "@typescript-eslint/prefer-namespace-keyword": "off", - "@typescript-eslint/prefer-readonly": "off", - "@typescript-eslint/prefer-regexp-exec": "warn", - "@typescript-eslint/prefer-string-starts-ends-with": "warn", - "@typescript-eslint/promise-function-async": "off", - "@typescript-eslint/require-array-sort-compare": "error", - "@typescript-eslint/require-await": "warn", - "@typescript-eslint/restrict-plus-operands": "off", - "@typescript-eslint/semi": "error", - "@typescript-eslint/strict-boolean-expressions": "off", - "@typescript-eslint/triple-slash-reference": "error", - "@typescript-eslint/type-annotation-spacing": "warn", - "@typescript-eslint/typedef": "off", - "@typescript-eslint/unbound-method": "off", - "@typescript-eslint/unified-signatures": "warn" - }, - "env": { - "browser": true, - "node": true, - "es6": true, - "jest": true - }, - "globals": { - "cc": false, - "wx": false, - "Editor": false, - "_Scene": false, - "_ccsg": false - } -} diff --git a/.eslintrc.yaml b/.eslintrc.yaml new file mode 100644 index 0000000000..1d5ababc29 --- /dev/null +++ b/.eslintrc.yaml @@ -0,0 +1,104 @@ +root: true + +parser: '@typescript-eslint/parser' + +parserOptions: + project: ./tsconfig.json + +extends: + - eslint:recommended + - airbnb-base + - plugin:@typescript-eslint/recommended + - plugin:@typescript-eslint/recommended-requiring-type-checking + +plugins: + - '@typescript-eslint' + +settings: + import/resolver: + node: + extensions: + - .js + - .jsx + - .ts + - .tsx + - .d.ts + +env: + browser: true + node: true + es6: true + jest: true + +globals: + cc: false + wx: false + Editor: false + _Scene: false + _ccsg: false + +rules: + + # https://eslint.org/docs/rules/ + # https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin + + ##### RECOMMENDED RULE OVERRIDES ##### + + camelcase: off # underscores may come in handy in some cases + eqeqeq: warn # important check missing from recommended + keyword-spacing: warn # we require this explicitly + no-multi-spaces: off # useful for manually align some expression across lines + prefer-rest-params: off # we need ES5 to be fast too + prefer-spread: off # we need ES5 to be fast too + space-before-function-paren: [warn, always] # we require this explicitly + + ##### AIRBNB-SPECIFIC RULE OVERRIDES ##### + + class-methods-use-this: off # so empty functions could work + guard-for-in: off # for-in is a efficient choice for plain objects + import/export: off # so export declare namespace could work + import/extensions: off # typescriptor doesn't support this + import/no-unresolved: off # TODO: fix internal modules + import/prefer-default-export: off # prefer seperate exports + indent: [warn, 4] # we use 4-space convention + lines-between-class-members: off # be more lenient on member declarations + max-classes-per-file: off # helper classes are common + max-len: [warn, 150] # more lenient on max length per line + new-cap: off # some class still doesn't follow this yet + no-underscore-dangle: off # allow underscores + no-plusplus: off # allow increment/decrement operators + no-console: off # allow console statements + no-continue: off # allow unlabeled continues + no-multi-assign: off # it is handy sometimes + no-param-reassign: off # the output object is passed as parameters all the time + no-restricted-syntax: off # for-in is a efficient choice for plain objects + no-return-assign: off # it is handy sometimes + no-shadow: off # TODO: this throws false-positives? + no-sequences: off # it is handy sometimes + no-bitwise: off # we use this extensively + no-use-before-define: off # just too much work + no-useless-constructor: off # gives false-positives for empty constructor with parameter properties + + ##### TYPESCRIPT-SPECIFIC RULE OVERRIDES ##### + + # TODO: this is just too much work + '@typescript-eslint/explicit-module-boundary-types': off + + # TODO: sadly we still rely heavily on legacyCC + '@typescript-eslint/no-unsafe-assignment': off + '@typescript-eslint/no-unsafe-call': off + '@typescript-eslint/no-unsafe-member-access': off + + '@typescript-eslint/unbound-method': off # we exploit prototype methods sometimes to acheive better performace + '@typescript-eslint/no-explicit-any': off # still relevant for some heavily templated usages + '@typescript-eslint/no-empty-function': off # may become useful in some parent classes + '@typescript-eslint/no-unused-vars': off # may become useful in some parent classes + '@typescript-eslint/no-non-null-assertion': off # sometimes we just know better than the compiler + '@typescript-eslint/no-namespace': [warn, { # we need to declare static properties + allowDeclarations: true, + allowDefinitionFiles: true + }] + '@typescript-eslint/restrict-template-expressions': [warn, { # concatenations of different types are common, e.g. hash calculations + allowNumber: true, + allowBoolean: true + }] diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 3ea7d92c9f..0000000000 --- a/.jshintrc +++ /dev/null @@ -1,42 +0,0 @@ -{ - "node": true, - "esnext": true, - "bitwise": false, - "camelcase": false, - "curly": false, - "eqeqeq": true, - "immed": true, - "indent": 4, - "latedef": false, - "newcap": false, - "noarg": true, - "quotmark": "single", - "undef": true, - "unused": true, - "strict": false, - "predef": [ - "window", - "document", - "Image", - "unused", - "Editor", - "EditorUI", - "Helper", - "_Scene", - "Polymer", - "sinon", - "after", - "afterAll", - "afterEach", - "assert", - "before", - "beforeAll", - "beforeEach", - "describe", - "expect", - "it", - "cc", - "wx", - "_ccsg" - ] -} diff --git a/.vscode/settings.json b/.vscode/settings.json index c9a2730ca3..4e4c38c0e9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -15,5 +15,8 @@ "eslint.validate": [ "javascript", "typescript" - ] + ], + "editor.codeActionsOnSave": { + "source.fixAll": true, + }, } diff --git a/@types/globals.d.ts b/@types/globals.d.ts index d3f2fe6541..920adfd655 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -25,6 +25,7 @@ */ declare const gfx: any; +declare const global: any; interface Window { @@ -62,7 +63,7 @@ interface HTMLElement{ } type ActiveXObject = new (s: string) => any; -declare var ActiveXObject: ActiveXObject; +declare const ActiveXObject: ActiveXObject; declare type CompareFunction = (a: T, b: T) => number; @@ -81,7 +82,7 @@ declare interface IWritableArrayLike { [index: number]: T; } -declare type Constructor = new(...args: any[]) => T; +declare type Constructor = new(...args: any[]) => T; declare type Mutable = { -readonly [P in keyof T]: T[P] }; diff --git a/cocos/audio/assets/clip.ts b/cocos/audio/assets/clip.ts index 1b4b0c6e46..fc9d247bd6 100644 --- a/cocos/audio/assets/clip.ts +++ b/cocos/audio/assets/clip.ts @@ -28,8 +28,10 @@ * @module component/audio */ +import { + ccclass, type, serializable, override, +} from 'cc.decorator'; import { Asset } from '../../core/assets/asset'; -import { ccclass, type, serializable, override } from 'cc.decorator'; import { Enum } from '../../core/value-types'; import { AudioPlayer, PlayingState } from './player'; import { AudioPlayerDOM } from './player-dom'; @@ -57,7 +59,6 @@ export const AudioType = Enum({ */ @ccclass('cc.AudioClip') export class AudioClip extends Asset { - public static PlayingState = PlayingState; public static AudioType = AudioType; public static preventDeferredLoadDependents = true; @@ -102,7 +103,12 @@ export class AudioClip extends Asset { @override get _nativeDep () { - return { uuid: this._uuid, audioLoadMode: this.loadMode, ext: this._native, __isNative__: true }; + return { + uuid: this._uuid, + audioLoadMode: this.loadMode, + ext: this._native, + __isNative__: true, + }; } get loadMode () { @@ -126,7 +132,7 @@ export class AudioClip extends Asset { public getLoop () { if (this._player) { return this._player.getLoop(); } return false; } private _getPlayer (clip: any) { - let ctor: any; + let ctor: Constructor; if (typeof AudioBuffer !== 'undefined' && clip instanceof AudioBuffer) { ctor = AudioPlayerWeb; this._loadMode = AudioType.WEB_AUDIO; diff --git a/cocos/audio/assets/player.ts b/cocos/audio/assets/player.ts index f0115fc168..c6d5abfb2b 100644 --- a/cocos/audio/assets/player.ts +++ b/cocos/audio/assets/player.ts @@ -70,6 +70,13 @@ export abstract class AudioPlayer { legacyCC.game.on(legacyCC.Game.EVENT_SHOW, this._onShow); } + public getState () { return this._state; } + public getDuration () { return this._duration; } + public destroy () { + legacyCC.game.off(legacyCC.Game.EVENT_HIDE, this._onHide); + legacyCC.game.off(legacyCC.Game.EVENT_SHOW, this._onShow); + } + public abstract play (): void; public abstract pause (): void; public abstract stop (): void; @@ -80,12 +87,6 @@ export abstract class AudioPlayer { public abstract getVolume (): number; public abstract setLoop (val: boolean): void; public abstract getLoop (): boolean; - public getState () { return this._state; } - public getDuration () { return this._duration; } - public destroy () { - legacyCC.game.off(legacyCC.Game.EVENT_HIDE, this._onHide); - legacyCC.game.off(legacyCC.Game.EVENT_SHOW, this._onShow); - } } legacyCC.internal.AudioPlayer = AudioPlayer; diff --git a/cocos/audio/audio-downloader.ts b/cocos/audio/audio-downloader.ts index 91e90cbf95..2a356a6aaf 100644 --- a/cocos/audio/audio-downloader.ts +++ b/cocos/audio/audio-downloader.ts @@ -44,13 +44,13 @@ export function downloadDomAudio ( url: string, options: IDownloadParseOptions, onComplete: CompleteCallback - ): void { +): void { createDomAudio(url).then(dom => { onComplete(null, dom); }, errMsg => { - log(errMsg); - onComplete(new Error(errMsg), null); + log(errMsg); + onComplete(new Error(errMsg), null); }); } @@ -61,7 +61,8 @@ function downloadArrayBuffer (url: string, options: IDownloadParseOptions, onCom export function downloadAudio (url: string, options: IDownloadParseOptions, onComplete: CompleteCallback) { if (formatSupport.length === 0) { - return onComplete(new Error(getError(4927))); + onComplete(new Error(getError(4927))); + return; } let handler: DownloadHandler | null = null; if (!__audioSupport.WEB_AUDIO) { @@ -77,4 +78,4 @@ export function downloadAudio (url: string, options: IDownloadParseOptions, onCo } } handler(url, options, onComplete); -}; +} diff --git a/cocos/audio/audio-utils.ts b/cocos/audio/audio-utils.ts index c5b87666d7..5fe0183a53 100644 --- a/cocos/audio/audio-utils.ts +++ b/cocos/audio/audio-utils.ts @@ -1,11 +1,12 @@ import { sys } from '../core/platform/sys'; -const __audioSupport = sys.__audioSupport; -export function createDomAudio (url): Promise { +const { __audioSupport } = sys; + +export function createDomAudio (url: string): Promise { return new Promise((resolve, reject) => { const dom = document.createElement('audio'); dom.src = url; - + const clearEvent = () => { clearTimeout(timer); dom.removeEventListener('canplaythrough', success, false); @@ -27,7 +28,7 @@ export function createDomAudio (url): Promise { }; const failure = () => { clearEvent(); - const message = 'load audio failure - ' + url; + const message = `load audio failure - ${url}`; reject(message); }; dom.addEventListener('canplaythrough', success, false); @@ -36,4 +37,4 @@ export function createDomAudio (url): Promise { dom.addEventListener(__audioSupport.USE_LOADER_EVENT, success, false); } }); -} \ No newline at end of file +} diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index c8de867015..e4a862b7d9 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -1,4 +1,4 @@ -// tslint:disable + // absolute essential effects export default [ { diff --git a/cocos/core/3d/builtin/shader-sources/glsl1.ts b/cocos/core/3d/builtin/shader-sources/glsl1.ts index 0ec39396fa..28f970f1bf 100644 --- a/cocos/core/3d/builtin/shader-sources/glsl1.ts +++ b/cocos/core/3d/builtin/shader-sources/glsl1.ts @@ -1,4 +1,4 @@ -// tslint:disable + export default [ [ { diff --git a/cocos/core/3d/builtin/shader-sources/glsl3.ts b/cocos/core/3d/builtin/shader-sources/glsl3.ts index 19d8afed7e..099c5ac447 100644 --- a/cocos/core/3d/builtin/shader-sources/glsl3.ts +++ b/cocos/core/3d/builtin/shader-sources/glsl3.ts @@ -1,4 +1,4 @@ -// tslint:disable + export default [ [ { diff --git a/cocos/core/3d/builtin/shader-sources/glsl4.ts b/cocos/core/3d/builtin/shader-sources/glsl4.ts index 4bdc0425b8..5fb2a280ed 100644 --- a/cocos/core/3d/builtin/shader-sources/glsl4.ts +++ b/cocos/core/3d/builtin/shader-sources/glsl4.ts @@ -1,4 +1,4 @@ -// tslint:disable + export default [ [ { diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index f60619afa1..602ec869ee 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -67,7 +67,7 @@ const ClearFlag = Enum({ DONT_CLEAR: GFXClearFlag.NONE, }); -// tslint:disable: no-shadowed-variable + export declare namespace Camera { export type ProjectionType = EnumAlias; export type FOVAxis = EnumAlias; @@ -76,7 +76,7 @@ export declare namespace Camera { export type Shutter = EnumAlias; export type ISO = EnumAlias; } -// tslint:enable: no-shadowed-variable + /** * @en The Camera Component. diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index 0f7d4a6449..2cd6ff0b6e 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -94,12 +94,12 @@ class StaticLightSettings { } } -// tslint:disable: no-shadowed-variable + export declare namespace Light { export type Type = EnumAlias; export type PhotometricTerm = EnumAlias; } -// tslint:enable: no-shadowed-variable + @ccclass('cc.Light') export class Light extends Component { diff --git a/cocos/core/3d/framework/mesh-renderer.ts b/cocos/core/3d/framework/mesh-renderer.ts index d84b3abce5..60ea7f0e52 100644 --- a/cocos/core/3d/framework/mesh-renderer.ts +++ b/cocos/core/3d/framework/mesh-renderer.ts @@ -371,7 +371,7 @@ export class MeshRenderer extends RenderableComponent { return; } const renderScene = this._getRenderScene(); - if (this._model.scene != null) { + if (this._model.scene !== null) { this._detachFromScene(); } renderScene.addModel(this._model); @@ -414,7 +414,7 @@ export class MeshRenderer extends RenderableComponent { this.lightmapSettings.uvParam.x, this.lightmapSettings.uvParam.y, this.lightmapSettings.uvParam.z, - this.lightmapSettings.uvParam.w + this.lightmapSettings.uvParam.w, ]); } diff --git a/cocos/core/3d/framework/renderable-component.ts b/cocos/core/3d/framework/renderable-component.ts index 5acc383f78..5373934b0b 100644 --- a/cocos/core/3d/framework/renderable-component.ts +++ b/cocos/core/3d/framework/renderable-component.ts @@ -4,9 +4,11 @@ */ import { EDITOR } from 'internal:constants'; +import { + ccclass, type, displayOrder, displayName, serializable, +} from 'cc.decorator'; import { Material } from '../../assets/material'; import { Component } from '../../components/component'; -import { ccclass, type, displayOrder, displayName, serializable } from 'cc.decorator'; import { IMaterialInstanceInfo, MaterialInstance } from '../../renderer/core/material-instance'; import { scene } from '../../renderer'; import { Layers } from '../../scene-graph/layers'; @@ -40,7 +42,7 @@ export class RenderableComponent extends Component { @displayName('Materials') get sharedMaterials () { // if we don't create an array copy, the editor will modify the original array directly. - return EDITOR && this._materials.slice() || this._materials; + return (EDITOR && this._materials.slice()) || this._materials; } set sharedMaterials (val) { @@ -79,7 +81,8 @@ export class RenderableComponent extends Component { } } for (let i = 0; i < this._materialInstances.length; i++) { - // tslint:disable-next-line: triple-equals // both of them may be undefined or null + // they could be either undefined or null + // eslint-disable-next-line eqeqeq if (this._materialInstances[i] != val[i]) { this.setMaterialInstance(i, val[i]); } @@ -87,6 +90,7 @@ export class RenderableComponent extends Component { } protected _materialInstances: (MaterialInstance | null)[] = []; + protected _models: scene.Model[] = []; get sharedMaterial () { @@ -166,10 +170,8 @@ export class RenderableComponent extends Component { this._materialInstances[index] = matInst as MaterialInstance; this._onMaterialModified(index, matInst); } - } else { - if (matInst !== this._materials[index]) { - this.setMaterial(matInst as Material, index); - } + } else if (matInst !== this._materials[index]) { + this.setMaterial(matInst as Material, index); } } diff --git a/cocos/core/3d/framework/skinned-mesh-batch-renderer.ts b/cocos/core/3d/framework/skinned-mesh-batch-renderer.ts index 29eb6b6eb1..7680f7da26 100644 --- a/cocos/core/3d/framework/skinned-mesh-batch-renderer.ts +++ b/cocos/core/3d/framework/skinned-mesh-batch-renderer.ts @@ -28,15 +28,19 @@ */ import { EDITOR } from 'internal:constants'; +import { + ccclass, help, executeInEditMode, executionOrder, menu, tooltip, type, visible, override, serializable, editable, +} from 'cc.decorator'; import { getWorldTransformUntilRoot } from '../../animation/transform-utils'; import { Filter, PixelFormat } from '../../assets/asset-enum'; import { Material } from '../../assets/material'; import { Mesh } from '../../assets/mesh'; import { Skeleton } from '../../assets/skeleton'; import { Texture2D } from '../../assets/texture-2d'; -import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, type, visible, override, serializable, editable } from 'cc.decorator'; import { CCString } from '../../data/utils/attribute'; -import { AttributeName, FormatInfos, Format, Type } from '../../gfx/define'; +import { + AttributeName, FormatInfos, Format, Type, +} from '../../gfx/define'; import { Device, Attribute, BufferTextureCopy } from '../../gfx'; import { Mat4, Vec2, Vec3 } from '../../math'; import { mapBuffer, readBuffer, writeBuffer } from '../misc/buffer'; @@ -50,7 +54,6 @@ const batch_extras_size = FormatInfos[batch_id.format].size + FormatInfos[batch_ @ccclass('cc.SkinnedMeshUnit') export class SkinnedMeshUnit { - /** * @en Skinned mesh of this unit. * @zh 子蒙皮模型的网格模型。 @@ -74,8 +77,10 @@ export class SkinnedMeshUnit { @serializable public _localTransform = new Mat4(); + @serializable private _offset = new Vec2(0, 0); + @serializable private _size = new Vec2(1, 1); @@ -87,6 +92,7 @@ export class SkinnedMeshUnit { set offset (offset) { Vec2.copy(this._offset, offset); } + get offset () { return this._offset; } @@ -99,6 +105,7 @@ export class SkinnedMeshUnit { set size (size) { Vec2.copy(this._size, size); } + get size () { return this._size; } @@ -115,6 +122,7 @@ export class SkinnedMeshUnit { this.material = comp.getMaterial(0); if (comp.skinningRoot) { getWorldTransformUntilRoot(comp.node, comp.skinningRoot, this._localTransform); } } + get copyFrom () { return null; } @@ -134,14 +142,13 @@ const v3_1 = new Vec3(); @executeInEditMode @menu('Components/SkinnedMeshBatchRenderer') export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { - /** * @en Size of the generated texture atlas. * @zh 合图生成的最终图集的边长。 */ @serializable @tooltip('i18n:batched_skinning_model.atlas_size') - public atlasSize: number = 1024; + public atlasSize = 1024; /** * @en @@ -165,6 +172,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { public units: SkinnedMeshUnit[] = []; private _textures: Record = {}; + private _batchMaterial: Material | null = null; @override @@ -172,6 +180,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { get mesh () { return super.mesh; } + set mesh (val) { super.mesh = val; } @@ -181,6 +190,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { get skeleton () { return super.skeleton; } + set skeleton (val) { super.skeleton = val; } @@ -328,9 +338,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { for (let i = 0; i < unitLen; i++) { const unit = this.units[i]; if (!unit || !unit.skeleton) { continue; } - jointIndexMap[i] = unit.skeleton.joints.map((j) => { - return this._skeleton!.joints.findIndex((ref) => j === ref); - }); + jointIndexMap[i] = unit.skeleton.joints.map((j) => this._skeleton!.joints.findIndex((ref) => j === ref)); } for (let i = 0; i < unitLen; i++) { @@ -339,8 +347,8 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { const newMesh = this._createUnitMesh(i, unit.mesh); const dataView = new DataView(newMesh.data.buffer); Mat4.inverseTranspose(m4_local, unit._localTransform); - const offset = unit.offset; - const size = unit.size; + const { offset } = unit; + const { size } = unit; for (let b = 0; b < newMesh.struct.vertexBundles.length; b++) { const bundle = newMesh.struct.vertexBundles[b]; // apply local transform to mesh @@ -436,7 +444,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { mapBuffer(dataView, (cur) => idxMap[cur], jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView); } } - this._mesh!.merge(newMesh); + this._mesh.merge(newMesh); } this._onMeshChanged(this._mesh); @@ -458,7 +466,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { region.texOffset.y = unit.offset.y * this.atlasSize; region.texExtent.width = unit.size.x * this.atlasSize; region.texExtent.height = unit.size.y * this.atlasSize; - const data = partial.image.data; + const { data } = partial.image; if (!ArrayBuffer.isView(data)) { texImages.push(data); texImageRegions.push(region); @@ -469,7 +477,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { } } const gfxTex = target.getGFXTexture()!; - const device: Device = legacyCC.director.root!.device; + const { device } = legacyCC.director.root!; if (texBuffers.length > 0) { device.copyBuffersToTexture(texBuffers, gfxTex, texBufferRegions); } if (texImages.length > 0) { device.copyTexImagesToTexture(texImages, gfxTex, texImageRegions); } } @@ -524,7 +532,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { if (uvFormat) { break; } } if (modifiedBundles[bundleIdx] !== undefined) { continue; } - modifiedBundles[bundleIdx] = [ uvFormat, uvOffset ]; + modifiedBundles[bundleIdx] = [uvFormat, uvOffset]; const newBundle = newMeshStruct.vertexBundles[bundleIdx]; // put the new UVs in the same bundle with original UVs newBundle.attributes.push(batch_id); newBundle.attributes.push(batch_uv); @@ -548,11 +556,11 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { const oldMeshData = mesh.data; const newDataView = new DataView(newMeshData.buffer); const oldDataView = new DataView(oldMeshData.buffer); - const isLittleEndian = legacyCC.sys.isLittleEndian; + const { isLittleEndian } = legacyCC.sys; for (const b in modifiedBundles) { const newBundle = newMeshStruct.vertexBundles[b]; const oldBundle = mesh.struct.vertexBundles[b]; - const [ uvFormat, uvOffset ] = modifiedBundles[b]; + const [uvFormat, uvOffset] = modifiedBundles[b]; const uvs = readBuffer(oldDataView, uvFormat, uvOffset, oldBundle.view.length, oldBundle.view.stride); const oldView = oldBundle.view; const newView = newBundle.view; @@ -564,7 +572,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { const srcVertex = oldMeshData.subarray(oldOffset, oldOffset + oldStride); newMeshData.set(srcVertex, newOffset); // insert batch ID - newDataView.setFloat32(newOffset + oldStride, unitIdx, ); + newDataView.setFloat32(newOffset + oldStride, unitIdx); // insert batch UV newDataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], isLittleEndian); newDataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], isLittleEndian); diff --git a/cocos/core/3d/framework/skinned-mesh-renderer.ts b/cocos/core/3d/framework/skinned-mesh-renderer.ts index 4fa959f8cf..ce9e403112 100644 --- a/cocos/core/3d/framework/skinned-mesh-renderer.ts +++ b/cocos/core/3d/framework/skinned-mesh-renderer.ts @@ -28,10 +28,12 @@ * @module model */ +import { + ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, +} from 'cc.decorator'; import { AnimationClip } from '../../animation/animation-clip'; import { Material } from '../../assets'; import { Skeleton } from '../../assets/skeleton'; -import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type } from 'cc.decorator'; import { models } from '../../renderer'; import { Node } from '../../scene-graph/node'; import { MeshRenderer } from './mesh-renderer'; @@ -48,7 +50,6 @@ import { legacyCC } from '../../global-exports'; @executeInEditMode @menu('Components/SkinnedMeshRenderer') export class SkinnedMeshRenderer extends MeshRenderer { - @type(Skeleton) protected _skeleton: Skeleton | null = null; diff --git a/cocos/core/3d/framework/spot-light-component.ts b/cocos/core/3d/framework/spot-light-component.ts index 9aacdaab71..6abf03290b 100644 --- a/cocos/core/3d/framework/spot-light-component.ts +++ b/cocos/core/3d/framework/spot-light-component.ts @@ -28,7 +28,9 @@ * @module component/light */ -import { ccclass, help, executeInEditMode, menu, tooltip, type, slide, range, unit, serializable } from 'cc.decorator'; +import { + ccclass, help, executeInEditMode, menu, tooltip, type, slide, range, unit, serializable, +} from 'cc.decorator'; import { toRadian } from '../../math'; import { scene } from '../../renderer'; import { Light, PhotometricTerm } from './light-component'; @@ -38,19 +40,23 @@ import { Light, PhotometricTerm } from './light-component'; @menu('Light/SpotLight') @executeInEditMode export class SpotLight extends Light { - @serializable protected _size = 0.15; + @serializable protected _luminance = 1700 / scene.nt2lm(0.15); + @serializable protected _term = PhotometricTerm.LUMINOUS_POWER; + @serializable protected _range = 1; + @serializable protected _spotAngle = 60; protected _type = scene.LightType.SPOT; + protected _light: scene.SpotLight | null = null; /** @@ -62,6 +68,7 @@ export class SpotLight extends Light { get luminousPower () { return this._luminance * scene.nt2lm(this._size); } + set luminousPower (val) { this._luminance = val / scene.nt2lm(this._size); if (this._light) { this._light.luminance = this._luminance; } @@ -76,6 +83,7 @@ export class SpotLight extends Light { get luminance () { return this._luminance; } + set luminance (val) { this._luminance = val; if (this._light) { this._light.luminance = val; } @@ -90,6 +98,7 @@ export class SpotLight extends Light { get term () { return this._term; } + set term (val) { this._term = val; } @@ -104,6 +113,7 @@ export class SpotLight extends Light { get size () { return this._size; } + set size (val) { this._size = val; if (this._light) { this._light.size = val; } @@ -119,6 +129,7 @@ export class SpotLight extends Light { get range () { return this._range; } + set range (val) { this._range = val; if (this._light) { this._light.range = val; } diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index b479c12257..ef1232254e 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -468,7 +468,7 @@ export class Animation extends Eventify(Component) { } private _removeStateOfAutomaticClip (clip: AnimationClip) { - // tslint:disable-next-line:forin + for (const name in this._nameToState) { const state = this._nameToState[name]; if (equalClips(clip, state.clip)) { diff --git a/cocos/core/animation/animation-curve.ts b/cocos/core/animation/animation-curve.ts index f23fe1b135..094a9230f3 100644 --- a/cocos/core/animation/animation-curve.ts +++ b/cocos/core/animation/animation-curve.ts @@ -342,7 +342,7 @@ const selectLerpFx = (() => { function makeValueTypeLerpFx (constructor: Constructor) { const tempValue = new constructor(); return (from: T, to: T, ratio: number) => { - // @ts-ignore + // @ts-expect-error constructor.lerp(tempValue, from, to, ratio); return tempValue; }; diff --git a/cocos/core/animation/cubic-spline-value.ts b/cocos/core/animation/cubic-spline-value.ts index 9fd874082b..28d65f7a39 100644 --- a/cocos/core/animation/cubic-spline-value.ts +++ b/cocos/core/animation/cubic-spline-value.ts @@ -72,7 +72,7 @@ function makeCubicSplineValueConstructor ( } } - // @ts-ignore TS2367 + // @ts-expect-error TS2367 if (constructorX === Quat) { const lerp = CubicSplineValueClass.prototype.lerp; CubicSplineValueClass.prototype.lerp = function (this: CubicSplineValueClass, to: CubicSplineValueClass, t: number, dt: number) { diff --git a/cocos/core/animation/motion-path-helper.ts b/cocos/core/animation/motion-path-helper.ts index b985c8aedc..fcfd562bad 100644 --- a/cocos/core/animation/motion-path-helper.ts +++ b/cocos/core/animation/motion-path-helper.ts @@ -9,7 +9,7 @@ import { Vec2, Vec3 } from '../math'; import { AnimCurve, computeRatioByType, CurveValue, EasingMethod } from './animation-curve'; import { bezier } from './bezier'; -// tslint:disable:no-shadowed-variable + export class Curve { public beziers: Bezier[] = []; @@ -248,7 +248,7 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, }; }; - // @ts-ignore + // @ts-expect-error const values = data.values = data.values.map((value) => { if (Array.isArray(value)) { value = value.length === 2 ? new Vec2(value[0], value[1]) : new Vec3(value[0], value[1], value[2]); @@ -282,13 +282,13 @@ export function sampleMotionPaths (motionPaths: Array<(MotionPath | undefined)>, } const types = data.types; - // @ts-ignore + // @ts-expect-error const ratios = (data.ratioSampler ? data.ratioSampler.ratios : []); - // @ts-ignore + // @ts-expect-error const newValues: CurveValue[] = data.values = []; const newTypes: any[] = data.types = []; - // @ts-ignore + // @ts-expect-error const newRatios: number[] = data.ratios = []; function addNewDatas (value: CurveValue, type: any, ratio: number) { diff --git a/cocos/core/animation/skeletal-animation-data-hub.ts b/cocos/core/animation/skeletal-animation-data-hub.ts index 557e7d3442..aa86fccc52 100644 --- a/cocos/core/animation/skeletal-animation-data-hub.ts +++ b/cocos/core/animation/skeletal-animation-data-hub.ts @@ -28,7 +28,9 @@ * @module animation */ -import { clamp01, Mat4, Quat, Vec3 } from '../math'; +import { + clamp01, Mat4, Quat, Vec3, +} from '../math'; import { DataPoolManager } from '../renderer/data-pool-manager'; import { AnimationClip, IObjectCurveData } from './animation-clip'; import { HierarchyPath, isCustomPath, isPropertyPath } from './target-path'; @@ -54,7 +56,6 @@ interface IConvertedData { * 骨骼动画数据转换中心。 */ export class SkelAnimDataHub { - public static getOrExtract (clip: AnimationClip) { let data = SkelAnimDataHub.pool.get(clip); if (!data || data.info.sample !== clip.sample) { @@ -76,10 +77,10 @@ export class SkelAnimDataHub { function convertToSkeletalCurves (clip: AnimationClip): IConvertedData { const data: Record = {}; clip.curves.forEach((curve) => { - if (!curve.valueAdapter && - isCustomPath(curve.modifiers[0], HierarchyPath) && - isPropertyPath(curve.modifiers[1])) { - const path = (curve.modifiers[0] as HierarchyPath).path; + if (!curve.valueAdapter + && isCustomPath(curve.modifiers[0], HierarchyPath) + && isPropertyPath(curve.modifiers[1])) { + const { path } = curve.modifiers[0]; let cs = data[path]; if (!cs) { cs = data[path] = {}; } const property = curve.modifiers[1] as string; @@ -126,8 +127,7 @@ function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, fra for (let i = 0, idx = 0; i < frames; i++) { let time = i / clip.sample; while (keys[idx] <= time) { idx++; } - if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } - else if (idx === 0) { idx = 1; } + if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } else if (idx === 0) { idx = 1; } const from = curve.values[idx - 1].clone(); const denom = keys[idx] - keys[idx - 1]; const ratio = denom ? clamp01((time - keys[idx - 1]) / denom) : 1; @@ -137,7 +137,7 @@ function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, fra (from as Vec3).lerp(curve.values[idx] as Vec3, ratio); } values[i] = from; - } + } } curve.values = values; } diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index 90a4f6fa73..943ae9c3f5 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -55,14 +55,20 @@ interface ISocketData { const noCurves: IRuntimeCurve[] = []; export class SkeletalAnimationState extends AnimationState { - protected _frames = 1; + protected _bakedDuration = 0; + protected _animInfo: IAnimInfo | null = null; + protected _sockets: ISocketData[] = []; + protected _animInfoMgr: JointAnimationInfo; + protected _comps: SkinnedMeshRenderer[] = []; + protected _parent: SkeletalAnimation | null = null; + protected _curvesInited = false; constructor (clip: AnimationClip, name = '') { @@ -84,7 +90,7 @@ export class SkeletalAnimationState extends AnimationState { const baked = this._parent.useBakedAnimation; super.initialize(root, baked ? noCurves : undefined); this._curvesInited = !baked; - const info = SkelAnimDataHub.getOrExtract(this.clip).info; + const { info } = SkelAnimDataHub.getOrExtract(this.clip); this._frames = info.frames - 1; this._animInfo = this._animInfoMgr.getData(root.uuid); this._bakedDuration = this._frames / info.sample; // last key @@ -113,7 +119,7 @@ export class SkeletalAnimationState extends AnimationState { public rebuildSocketCurves (sockets: Socket[]) { this._sockets.length = 0; - if (!this._targetNode) { return null; } + if (!this._targetNode) { return; } const root = this._targetNode; for (let i = 0; i < sockets.length; ++i) { const socket = sockets[i]; @@ -137,7 +143,7 @@ export class SkeletalAnimationState extends AnimationState { if (idx < 0) { break; } } const curveData: Mat4[] | undefined = source && source.worldMatrix.values as Mat4[]; - const frames = clipData.info.frames; + const { frames } = clipData.info; const transforms: ITransform[] = []; for (let f = 0; f < frames; f++) { let mat: Mat4; diff --git a/cocos/core/animation/skeletal-animation.ts b/cocos/core/animation/skeletal-animation.ts index 99f2a5c08d..168f33adb0 100644 --- a/cocos/core/animation/skeletal-animation.ts +++ b/cocos/core/animation/skeletal-animation.ts @@ -28,8 +28,10 @@ * @module animation */ +import { + ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, serializable, editable, +} from 'cc.decorator'; import { SkinnedMeshRenderer } from '../3d/framework/skinned-mesh-renderer'; -import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, serializable, editable } from 'cc.decorator'; import { Mat4 } from '../math'; import { DataPoolManager } from '../renderer/data-pool-manager'; import { Node } from '../scene-graph/node'; @@ -44,14 +46,13 @@ import { js } from '../utils/js'; @ccclass('cc.SkeletalAnimation.Socket') export class Socket { - /** * @en Path of the target joint. * @zh 此挂点的目标骨骼路径。 */ @serializable @editable - public path: string = ''; + public path = ''; /** * @en Transform output node. @@ -99,7 +100,6 @@ function collectRecursively (node: Node, prefix = '', out: string[] = []) { @executeInEditMode @menu('Components/SkeletalAnimation') export class SkeletalAnimation extends Animation { - public static Socket = Socket; /** @@ -114,6 +114,7 @@ export class SkeletalAnimation extends Animation { get sockets () { return this._sockets; } + set sockets (val) { if (!this._useBakedAnimation) { const animMgr = legacyCC.director.getAnimationManager() as AnimationManager; @@ -137,6 +138,7 @@ export class SkeletalAnimation extends Animation { get useBakedAnimation () { return this._useBakedAnimation; } + set useBakedAnimation (val) { this._useBakedAnimation = val; const comps = this.node.getComponentsInChildren(SkinnedMeshRenderer); @@ -146,8 +148,11 @@ export class SkeletalAnimation extends Animation { comp.setUseBakedAnimation(this._useBakedAnimation); } } - if (this._useBakedAnimation) { (legacyCC.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets); } - else { (legacyCC.director.getAnimationManager() as AnimationManager).addSockets(this.node, this._sockets); } + if (this._useBakedAnimation) { + (legacyCC.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets); + } else { + (legacyCC.director.getAnimationManager() as AnimationManager).addSockets(this.node, this._sockets); + } } @serializable @@ -169,8 +174,8 @@ export class SkeletalAnimation extends Animation { } public querySockets () { - const animPaths = this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).data).sort().reduce((acc, cur) => - cur.startsWith(acc[acc.length - 1]) ? acc : (acc.push(cur), acc), [] as string[]) || []; + const animPaths = (this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).data).sort() + .reduce((acc, cur) => (cur.startsWith(acc[acc.length - 1]) ? acc : (acc.push(cur), acc)), [] as string[])) || []; if (!animPaths.length) { return ['please specify a valid default animation clip first']; } const out: string[] = []; for (let i = 0; i < animPaths.length; i++) { @@ -186,7 +191,7 @@ export class SkeletalAnimation extends Animation { public rebuildSocketAnimations () { for (const socket of this._sockets) { const joint = this.node.getChildByPath(socket.path); - const target = socket.target; + const { target } = socket; if (joint && target) { target.name = `${socket.path.substring(socket.path.lastIndexOf('/') + 1)} Socket`; target.parent = this.node; diff --git a/cocos/core/asset-manager/asset-manager.ts b/cocos/core/asset-manager/asset-manager.ts index 841b48a0e8..c7a7243ec9 100644 --- a/cocos/core/asset-manager/asset-manager.ts +++ b/cocos/core/asset-manager/asset-manager.ts @@ -47,12 +47,12 @@ import { IPipe, Pipeline } from './pipeline'; import preprocess from './preprocess'; import releaseManager from './release-manager'; import RequestItem from './request-item'; -import { +import { CompleteCallback, CompleteCallbackNoData, ProgressCallback, IBundleOptions, - INativeAssetOptions, + INativeAssetOptions, IOptions, IRemoteOptions, presets, @@ -520,7 +520,7 @@ export class AssetManager { public postLoadNative (asset: Asset, options?: INativeAssetOptions | CompleteCallbackNoData | null, onComplete?: CompleteCallbackNoData | null) { const { options: opts, onComplete: onComp } = parseParameters(options, undefined, onComplete); - // @ts-ignore + // @ts-expect-error if (!asset._native || !asset.__nativeDepend__) { return asyncify(onComp)(null); } @@ -536,10 +536,10 @@ export class AssetManager { this.loadAny(depend, opts, (err, native) => { if (!err) { - // @ts-ignore + // @ts-expect-error if (asset.isValid && asset.__nativeDepend__) { asset._nativeAsset = native; - // @ts-ignore + // @ts-expect-error asset.__nativeDepend__ = false; } } diff --git a/cocos/core/asset-manager/bundle.ts b/cocos/core/asset-manager/bundle.ts index 2d5a1d8973..b49e7f7660 100644 --- a/cocos/core/asset-manager/bundle.ts +++ b/cocos/core/asset-manager/bundle.ts @@ -424,7 +424,7 @@ export default class Bundle { } else if (sceneAsset instanceof SceneAsset && sceneAsset.scene) { const scene = sceneAsset.scene; - // @ts-ignore + // @ts-expect-error scene._id = sceneAsset._uuid; scene.name = sceneAsset.name; if (onComp) { onComp(null, sceneAsset); } diff --git a/cocos/core/asset-manager/depend-util.ts b/cocos/core/asset-manager/depend-util.ts index a4beb04b55..a5b89de1db 100644 --- a/cocos/core/asset-manager/depend-util.ts +++ b/cocos/core/asset-manager/depend-util.ts @@ -153,7 +153,7 @@ export class DependUtil { return this._depends.get(uuid)!; } - // @ts-ignore + // @ts-expect-error if (Array.isArray(json) && (!(BUILD || isCompiledJson(json)) || !hasNativeDep(json))) { out = { deps: this._parseDepsFromJson(json), @@ -196,13 +196,13 @@ export class DependUtil { preventPreloadNativeObject: (asset.constructor as typeof Asset).preventPreloadNativeObject, preventDeferredLoadDependents: (asset.constructor as typeof Asset).preventDeferredLoadDependents, }; - // @ts-ignore + // @ts-expect-error const deps = asset.__depends__ as IDependProp[]; for (let i = 0, l = deps.length; i < l; i++) { out.deps.push(deps[i].uuid); } - // @ts-ignore + // @ts-expect-error if (asset.__nativeDepend__) { out.nativeDep = asset._nativeDep; } @@ -214,7 +214,7 @@ export class DependUtil { let depends: string[] | null = null; if (DEV) { if (isCompiledJson(json)) { - // @ts-ignore + // @ts-expect-error depends = getDependUuidList(json); depends!.forEach((uuid, index) => depends![index] = decodeUuid(uuid)); return depends!; @@ -242,7 +242,7 @@ export class DependUtil { return depends; } else { - // @ts-ignore + // @ts-expect-error depends = getDependUuidList(json); depends!.forEach((uuid, index) => depends![index] = decodeUuid(uuid)); } diff --git a/cocos/core/asset-manager/deprecated.ts b/cocos/core/asset-manager/deprecated.ts index 57e1298650..11298097b5 100644 --- a/cocos/core/asset-manager/deprecated.ts +++ b/cocos/core/asset-manager/deprecated.ts @@ -81,7 +81,7 @@ const md5Pipe = { return match + '.' + hashValue; }); } - + return url; }, }; @@ -113,7 +113,7 @@ export class CCLoader { private _parseLoadResArgs = parseLoadResArgs; public get _cache () { - // @ts-ignore + // @ts-expect-error return assets._map; } @@ -414,7 +414,7 @@ export class CCLoader { return info.path; }); } - // @ts-ignore + // @ts-expect-error if (onComplete) { onComplete(err, out, urls); } }); } diff --git a/cocos/core/asset-manager/factory.ts b/cocos/core/asset-manager/factory.ts index 6726b351e0..5617ef7018 100644 --- a/cocos/core/asset-manager/factory.ts +++ b/cocos/core/asset-manager/factory.ts @@ -30,14 +30,19 @@ import { AudioClip } from '../../audio/assets/clip'; import { VideoClip } from '../../video/assets/video-clip'; -import { ImageAsset, JsonAsset, TextAsset, TTFFont, Asset } from '../assets'; +import { + ImageAsset, JsonAsset, TextAsset, TTFFont, Asset, +} from '../assets'; import { BufferAsset } from '../assets/buffer-asset'; import { js } from '../utils/js'; import Bundle, { resources } from './bundle'; import Cache from './cache'; import { IConfigOption } from './config'; -import { assets, BuiltinBundleName, bundles, CompleteCallback, IRemoteOptions } from './shared'; -import { IDownloadParseOptions } from './shared'; +import { + assets, BuiltinBundleName, bundles, CompleteCallback, IRemoteOptions, + IDownloadParseOptions, +} from './shared'; + import { cache } from './utilities'; export type CreateHandler = (id: string, data: any, options: IDownloadParseOptions, onComplete: CompleteCallback) => void; @@ -49,8 +54,7 @@ function createImageAsset (id: string, data: HTMLImageElement, options: IDownloa out = new ImageAsset(); out._nativeUrl = id; out._nativeAsset = data; - } - catch (e) { + } catch (e) { err = e; } onComplete(err, out); @@ -60,7 +64,7 @@ function createAudioClip (id: string, data: HTMLAudioElement | AudioBuffer, opti const out = new AudioClip(); out._nativeUrl = id; out._nativeAsset = data; - // @ts-ignore + // @ts-expect-error assignment to private field out._duration = data.duration; onComplete(null, out); } @@ -102,42 +106,41 @@ function createBundle (id: string, data: IConfigOption, options: IDownloadParseO let bundle = bundles.get(data.name); if (!bundle) { bundle = data.name === BuiltinBundleName.RESOURCES ? resources : new Bundle(); - data.base = data.base || id + '/'; + data.base = data.base || `${id}/`; bundle.init(data); } onComplete(null, bundle); } function createVideoClip (id: string, data: HTMLVideoElement, options: IDownloadParseOptions, onComplete: CompleteCallback) { - let out = new VideoClip(); + const out = new VideoClip(); out._nativeUrl = id; out._nativeAsset = data; onComplete(null, out); } export class Factory { - private _creating = new Cache(); private _producers: Record = { // Images - '.png' : createImageAsset, - '.jpg' : createImageAsset, - '.bmp' : createImageAsset, - '.jpeg' : createImageAsset, - '.gif' : createImageAsset, - '.ico' : createImageAsset, - '.tiff' : createImageAsset, - '.webp' : createImageAsset, - '.image' : createImageAsset, + '.png': createImageAsset, + '.jpg': createImageAsset, + '.bmp': createImageAsset, + '.jpeg': createImageAsset, + '.gif': createImageAsset, + '.ico': createImageAsset, + '.tiff': createImageAsset, + '.webp': createImageAsset, + '.image': createImageAsset, '.pvr': createImageAsset, '.pkm': createImageAsset, // Audio - '.mp3' : createAudioClip, - '.ogg' : createAudioClip, - '.wav' : createAudioClip, - '.m4a' : createAudioClip, + '.mp3': createAudioClip, + '.ogg': createAudioClip, + '.wav': createAudioClip, + '.m4a': createAudioClip, // Video '.mp4': createVideoClip, @@ -149,26 +152,26 @@ export class Factory { '.rmvb': createVideoClip, // Txt - '.txt' : createTextAsset, - '.xml' : createTextAsset, - '.vsh' : createTextAsset, - '.fsh' : createTextAsset, - '.atlas' : createTextAsset, + '.txt': createTextAsset, + '.xml': createTextAsset, + '.vsh': createTextAsset, + '.fsh': createTextAsset, + '.atlas': createTextAsset, - '.tmx' : createTextAsset, - '.tsx' : createTextAsset, - '.fnt' : createTextAsset, + '.tmx': createTextAsset, + '.tsx': createTextAsset, + '.fnt': createTextAsset, - '.json' : createJsonAsset, - '.ExportJson' : createJsonAsset, + '.json': createJsonAsset, + '.ExportJson': createJsonAsset, // font - '.font' : createFont, - '.eot' : createFont, - '.ttf' : createFont, - '.woff' : createFont, - '.svg' : createFont, - '.ttc' : createFont, + '.font': createFont, + '.eot': createFont, + '.ttf': createFont, + '.woff': createFont, + '.svg': createFont, + '.ttc': createFont, // Binary '.binary': createBufferAsset, @@ -176,17 +179,16 @@ export class Factory { '.dbbin': createBufferAsset, '.skel': createBufferAsset, - 'bundle': createBundle, + bundle: createBundle, - 'default': createAsset, + default: createAsset, }; public register (type: string | Record, handler?: CreateHandler): void { if (typeof type === 'object') { js.mixin(this._producers, type); - } - else { + } else { this._producers[type] = handler!; } } @@ -195,7 +197,8 @@ export class Factory { const handler = this._producers[type] || this._producers.default; const asset = assets.get(id); if (!options.reloadAsset && asset) { - return onComplete(null, asset); + onComplete(null, asset); + return; } const creating = this._creating.get(id); if (creating) { diff --git a/cocos/core/asset-manager/fetch.ts b/cocos/core/asset-manager/fetch.ts index d54a10399e..258e5862a7 100644 --- a/cocos/core/asset-manager/fetch.ts +++ b/cocos/core/asset-manager/fetch.ts @@ -57,7 +57,7 @@ export default function fetch (task: Task, done: CompleteCallbackNoData) { if (!item.isNative && assets.has(item.uuid)) { const asset = assets.get(item.uuid); asset!.addRef(); - // @ts-ignore + // @ts-expect-error handle(item, task, asset, null, asset.__asyncLoadAssets__, depends, total, done); return cb(); } diff --git a/cocos/core/asset-manager/font-loader.ts b/cocos/core/asset-manager/font-loader.ts index 7af8170671..8f0e6da88f 100644 --- a/cocos/core/asset-manager/font-loader.ts +++ b/cocos/core/asset-manager/font-loader.ts @@ -124,7 +124,7 @@ function nativeCheckFontLoaded (start: number, font: string, callback: CompleteC reject(); } else { - // @ts-ignore + // @ts-expect-error document.fonts.load('40px ' + font).then((fonts) => { if (fonts.length >= 1) { resolve(); @@ -236,4 +236,4 @@ export function _getFontFamily (fontHandle: string): string { fontFamilyName = '"' + fontFamilyName + '"'; } return fontFamilyName; -} \ No newline at end of file +} diff --git a/cocos/core/asset-manager/load.ts b/cocos/core/asset-manager/load.ts index fded69604f..dff16de303 100644 --- a/cocos/core/asset-manager/load.ts +++ b/cocos/core/asset-manager/load.ts @@ -159,7 +159,7 @@ const loadOneAssetPipeline = new Pipeline('loadOneAsset', [ else { if (!options.reloadAsset && assets.has(uuid)) { const asset = assets.get(uuid)!; - // @ts-ignore + // @ts-expect-error if (options.__asyncLoadAssets__ || !asset.__asyncLoadAssets__) { item.content = asset.addRef(); if (progress.canInvoke) { @@ -207,7 +207,7 @@ function loadDepends (task: Task, asset: Asset, done: CompleteCallbackNoData, in progress, onComplete: (err) => { asset.decRef && asset.decRef(false); - // @ts-ignore + // @ts-expect-error asset.__asyncLoadAssets__ = __asyncLoadAssets__; repeatItem.finish = true; repeatItem.err = err; @@ -222,7 +222,7 @@ function loadDepends (task: Task, asset: Asset, done: CompleteCallbackNoData, in } if (!init) { - // @ts-ignore + // @ts-expect-error if (asset.__nativeDepend__) { if (!setProperties(uuid, asset, map)) { try { diff --git a/cocos/core/asset-manager/pack-manager.ts b/cocos/core/asset-manager/pack-manager.ts index f5762a5785..196a843074 100644 --- a/cocos/core/asset-manager/pack-manager.ts +++ b/cocos/core/asset-manager/pack-manager.ts @@ -89,7 +89,7 @@ export class PackManager { if (Array.isArray(json)) { - // @ts-ignore + // @ts-expect-error json = unpackJSONs(json, MissingScript.safeFindClass); if (json.length !== pack.length) { diff --git a/cocos/core/asset-manager/release-manager.ts b/cocos/core/asset-manager/release-manager.ts index 53a26fc4c6..e50f70ea1a 100644 --- a/cocos/core/asset-manager/release-manager.ts +++ b/cocos/core/asset-manager/release-manager.ts @@ -163,7 +163,7 @@ class ReleaseManager { // transfer refs from persist nodes to new scene for (let i = 0, l = persistNodes.length; i < l; i++) { const node = persistNodes[i]; - // @ts-ignore + // @ts-expect-error const sceneDeps = dependUtil._depends.get(newScene._id); const deps = this._persistNodeDeps.get(node.uuid) as string[]; for (const dep of deps) { @@ -182,7 +182,7 @@ class ReleaseManager { if (!oldScene) { return; } - // @ts-ignore + // @ts-expect-error const childs = dependUtil.getDeps(oldScene._id); for (let i = 0, l = childs.length; i < l; i++) { const asset = assets.get(childs[i]); @@ -190,7 +190,7 @@ class ReleaseManager { asset.decRef(TEST || oldScene.autoReleaseAssets); } } - // @ts-ignore + // @ts-expect-error const dependencies = dependUtil._depends.get(oldScene._id); if (dependencies && dependencies.persistDeps) { const persistDeps = dependencies.persistDeps; @@ -201,7 +201,7 @@ class ReleaseManager { } } } - // @ts-ignore + // @ts-expect-error dependUtil.remove(oldScene._id); } diff --git a/cocos/core/asset-manager/utilities.ts b/cocos/core/asset-manager/utilities.ts index 4eec518e32..362bb21bc4 100644 --- a/cocos/core/asset-manager/utilities.ts +++ b/cocos/core/asset-manager/utilities.ts @@ -94,7 +94,7 @@ export function getDepends (uuid: string, data: Asset | Record, exc try { const info = dependUtil.parse(uuid, data); let includeNative = true; - // @ts-ignore + // @ts-expect-error if (data instanceof Asset && (!data.__nativeDepend__)) { includeNative = false; } if (!preload) { asyncLoadAssets = !EDITOR && (!!(data as SceneAsset|Prefab).asyncLoadAssets || (asyncLoadAssets && !info.preventDeferredLoadDependents)); @@ -145,7 +145,7 @@ export function cache (id: string, asset: Asset, cacheAsset?: boolean) { export function setProperties (uuid: string, asset: Asset, assetsMap: Record) { let missingAsset = false; - // @ts-ignore + // @ts-expect-error const depends = asset.__depends__ as IDependProp[]; if (depends) { let missingAssetReporter: any = null; @@ -180,11 +180,11 @@ export function setProperties (uuid: string, asset: Asset, assetsMap: Record void; -// @ts-ignore +// @ts-expect-error Asset.prototype.createNode = null; legacyCC.Asset = Asset; diff --git a/cocos/core/assets/deprecation.ts b/cocos/core/assets/deprecation.ts index bc112d694a..29ddd3b74b 100644 --- a/cocos/core/assets/deprecation.ts +++ b/cocos/core/assets/deprecation.ts @@ -40,7 +40,7 @@ replaceProperty(RenderTexture.prototype, 'RenderTexture.prototype', [ { name: 'getGFXWindow', customFunction () { - // @ts-ignore + // @ts-expect-error return this._window; }, }, diff --git a/cocos/core/assets/label-atlas.ts b/cocos/core/assets/label-atlas.ts index ce74e7b937..92502d7a11 100644 --- a/cocos/core/assets/label-atlas.ts +++ b/cocos/core/assets/label-atlas.ts @@ -38,7 +38,7 @@ import { legacyCC } from '../global-exports'; * */ @ccclass('cc.LabelAtlas') -export class LabelAtlas extends BitmapFont{ +export class LabelAtlas extends BitmapFont { } legacyCC.LabelAtlas = LabelAtlas; diff --git a/cocos/core/assets/material.ts b/cocos/core/assets/material.ts index b181319f5b..9f29c55b57 100644 --- a/cocos/core/assets/material.ts +++ b/cocos/core/assets/material.ts @@ -28,18 +28,18 @@ * @module material */ -import { ccclass, type, serializable } from 'cc.decorator'; -import { builtinResMgr } from '../3d/builtin/init'; -import { RenderableComponent } from '../3d/framework/renderable-component'; -import { Texture } from '../gfx'; -import { MacroRecord, MaterialProperty, PropertyType } from '../renderer/core/pass-utils'; -import { IPassInfoFull, Pass, PassOverrides } from '../renderer/core/pass'; -import { legacyCC } from '../global-exports'; +import { ccclass, serializable, type } from 'cc.decorator'; import { Asset } from './asset'; import { EffectAsset } from './effect-asset'; -import { SpriteFrame } from './sprite-frame'; -import { TextureBase } from './texture-base'; import { RenderTexture } from './render-texture'; +import { RenderableComponent } from '../3d/framework/renderable-component'; +import { SpriteFrame } from './sprite-frame'; +import { Texture } from '../gfx'; +import { TextureBase } from './texture-base'; +import { builtinResMgr } from '../3d/builtin/init'; +import { legacyCC } from '../global-exports'; +import { IPassInfoFull, Pass, PassOverrides } from '../renderer/core/pass'; +import { MacroRecord, MaterialProperty, PropertyType } from '../renderer/core/pass-utils'; /** * @en The basic infos for material initialization. @@ -91,7 +91,6 @@ type MaterialPropertyFull = MaterialProperty | TextureBase | SpriteFrame | Rende */ @ccclass('cc.Material') export class Material extends Asset { - /** * @en Get hash for a material * @zh 获取一个材质的哈希值 @@ -107,18 +106,28 @@ export class Material extends Asset { @type(EffectAsset) protected _effectAsset: EffectAsset | null = null; + @serializable protected _techIdx = 0; + @serializable protected _defines: MacroRecord[] = []; + @serializable protected _states: PassOverrides[] = []; + @serializable protected _props: Record[] = []; protected _passes: Pass[] = []; + protected _hash = 0; + constructor () { + super(); + this.loaded = false; + } + /** * @en The current [[EffectAsset]]. * @zh 当前使用的 [[EffectAsset]] 资源。 @@ -175,11 +184,6 @@ export class Material extends Asset { return null; } - constructor () { - super(); - this.loaded = false; - } - /** * @en Initialize this material with the given information. * @zh 根据所给信息初始化这个材质,初始化正常结束后材质即可立即用于渲染。 @@ -190,12 +194,16 @@ export class Material extends Asset { if (!this._states) { this._states = []; } if (!this._props) { this._props = []; } if (info.technique !== undefined) { this._techIdx = info.technique; } - if (info.effectAsset) { this._effectAsset = info.effectAsset; } - else if (info.effectName) { this._effectAsset = EffectAsset.get(info.effectName); } + if (info.effectAsset) { + this._effectAsset = info.effectAsset; + } else if (info.effectName) { + this._effectAsset = EffectAsset.get(info.effectName); + } if (info.defines) { this._prepareInfo(info.defines, this._defines); } if (info.states) { this._prepareInfo(info.states, this._states); } this._update(); } + public reset (info: IMaterialInfo) { // to be consistent with other assets this.initialize(info); } @@ -221,7 +229,7 @@ export class Material extends Asset { * @param passIdx The pass to apply to. Will apply to all passes if not specified. */ public recompileShaders (overrides: MacroRecord, passIdx?: number) { - console.warn('Shaders in material asset \'' + this.name + '\' cannot be modified at runtime, please instantiate the material first.'); + console.warn(`Shaders in material asset '${this.name}' cannot be modified at runtime, please instantiate the material first.`); } /** @@ -231,7 +239,7 @@ export class Material extends Asset { * @param passIdx The pass to apply to. Will apply to all passes if not specified. */ public overridePipelineStates (overrides: PassOverrides, passIdx?: number) { - console.warn('Pipeline states in material asset \'' + this.name + '\' cannot be modified at runtime, please instantiate the material first.'); + console.warn(`Pipeline states in material asset '${this.name}' cannot be modified at runtime, please instantiate the material first.`); } /** @@ -292,7 +300,6 @@ export class Material extends Asset { } if (!success) { console.warn(`illegal property name: ${name}.`); - return; } } @@ -333,27 +340,28 @@ export class Material extends Asset { this._techIdx = mat._techIdx; this._props.length = mat._props.length; for (let i = 0; i < mat._props.length; i++) { - this._props[i] = Object.assign({}, mat._props[i]); + this._props[i] = { ...mat._props[i] }; } this._defines.length = mat._defines.length; for (let i = 0; i < mat._defines.length; i++) { - this._defines[i] = Object.assign({}, mat._defines[i]); + this._defines[i] = { ...mat._defines[i] }; } this._states.length = mat._states.length; for (let i = 0; i < mat._states.length; i++) { - this._states[i] = Object.assign({}, mat._states[i]); + this._states[i] = { ...mat._states[i] }; } this._effectAsset = mat._effectAsset; this._update(); } - protected _prepareInfo (patch: object | object[], cur: object[]) { - if (!Array.isArray(patch)) { // fill all the passes if not specified + protected _prepareInfo (patch: Record | Record[], cur: Record[]) { + let patchArray = patch; + if (!Array.isArray(patchArray)) { // fill all the passes if not specified const len = this._effectAsset ? this._effectAsset.techniques[this._techIdx].passes.length : 1; - patch = Array(len).fill(patch); + patchArray = Array(len).fill(patchArray); } - for (let i = 0; i < (patch as object[]).length; ++i) { - Object.assign(cur[i] || (cur[i] = {}), patch[i]); + for (let i = 0; i < patchArray.length; ++i) { + Object.assign(cur[i] || (cur[i] = {}), patchArray[i]); } } @@ -382,7 +390,7 @@ export class Material extends Asset { return passes; } - protected _update (keepProps: boolean = true) { + protected _update (keepProps = true) { if (this._effectAsset) { if (this._passes && this._passes.length) { for (const pass of this._passes) { @@ -446,7 +454,7 @@ export class Material extends Asset { const texture: Texture | null = val.getGFXTexture(); if (!texture || !texture.width || !texture.height) { // console.warn(`material '${this._uuid}' received incomplete texture asset '${val._uuid}'`); - return false; + return; } pass.bindTexture(binding, texture, index); pass.bindSampler(binding, val.getGFXSampler(), index); diff --git a/cocos/core/assets/mesh.ts b/cocos/core/assets/mesh.ts index fd3f36b495..55e755407c 100644 --- a/cocos/core/assets/mesh.ts +++ b/cocos/core/assets/mesh.ts @@ -29,39 +29,44 @@ */ import { ccclass, serializable } from 'cc.decorator'; -import { Mat4, Quat, Vec3 } from '../../core/math'; -import { mapBuffer } from '../3d/misc/buffer'; +import { Asset } from './asset'; import { BufferBlob } from '../3d/misc/buffer-blob'; +import { Skeleton } from './skeleton'; import { aabb } from '../geometry'; -import { Buffer, BufferInfo } from '../gfx'; +import { legacyCC } from '../global-exports'; +import { mapBuffer } from '../3d/misc/buffer'; +import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; +import { sys } from '../platform/sys'; +import { warnID } from '../platform/debug'; +import { + Attribute, Device, InputAssemblerInfo, Buffer, BufferInfo, +} from '../gfx'; import { - getTypedArrayConstructor, AttributeName, BufferUsageBit, + Feature, Format, FormatInfos, FormatType, MemoryUsageBit, PrimitiveMode, - Feature + getTypedArrayConstructor, } from '../gfx/define'; -import { Device, Attribute, InputAssemblerInfo } from '../gfx'; -import { warnID } from '../platform/debug'; -import { sys } from '../platform/sys'; -import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; -import { Asset } from './asset'; -import { Skeleton } from './skeleton'; -import { Morph, createMorphRendering, MorphRendering } from './morph'; -import { legacyCC } from '../global-exports'; -import { FlatBufferArrayPool, FlatBufferPool, FlatBufferView, freeHandleArray, NULL_HANDLE, RawBufferPool, SubMeshHandle, SubMeshPool, SubMeshView } from '../renderer/core/memory-pools'; + +import { + FlatBufferArrayPool, FlatBufferPool, FlatBufferView, NULL_HANDLE, RawBufferPool, + SubMeshHandle, SubMeshPool, SubMeshView, freeHandleArray, +} from '../renderer/core/memory-pools'; +import { Mat4, Quat, Vec3 } from '../math'; +import { Morph, MorphRendering, createMorphRendering } from './morph'; function getIndexStrideCtor (stride: number) { switch (stride) { - case 1: return Uint8Array; - case 2: return Uint16Array; - case 4: return Uint32Array; + case 1: return Uint8Array; + case 2: return Uint16Array; + case 4: return Uint32Array; + default: return Uint8Array; } - return Uint8Array; } /** @@ -97,7 +102,7 @@ export interface IGeometricInfo { * @en The bounding box * @zh 此几何体的轴对齐包围盒。 */ - boundingBox: { max: Vec3; min: Vec3; } + boundingBox: { max: Vec3; min: Vec3 }; } /** @@ -115,22 +120,67 @@ export interface IFlatBuffer { * @zh 包含所有顶点数据的渲染子网格,可以用来创建 [[InputAssembler]]。 */ export class RenderingSubMesh { + public mesh?: Mesh; + + public subMeshIdx?: number; + + private _flatBuffers: IFlatBuffer[] = []; + + private _jointMappedBuffers?: Buffer[]; + + private _jointMappedBufferIndices?: number[]; + + private _vertexIdChannel?: { stream: number; index: number }; + + private _geometricInfo?: IGeometricInfo; + + private _vertexBuffers: Buffer[]; + + private _attributes: Attribute[]; + + private _indexBuffer: Buffer | null = null; + + private _indirectBuffer: Buffer | null = null; + + private _primitiveMode: PrimitiveMode; + + private _iaInfo: InputAssemblerInfo; + + private _handle: SubMeshHandle = NULL_HANDLE; + + constructor ( + vertexBuffers: Buffer[], attributes: Attribute[], primitiveMode: PrimitiveMode, + indexBuffer: Buffer | null = null, indirectBuffer: Buffer | null = null, + ) { + this._attributes = attributes; + this._vertexBuffers = vertexBuffers; + this._indexBuffer = indexBuffer; + this._indirectBuffer = indirectBuffer; + this._primitiveMode = primitiveMode; + this._iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer); + this._handle = SubMeshPool.alloc(); + const fbArrayHandle = FlatBufferArrayPool.alloc(); + SubMeshPool.set(this._handle, SubMeshView.FLAT_BUFFER_ARRAY, fbArrayHandle); + } /** * @en All vertex attributes used by the sub mesh * @zh 所有顶点属性。 */ get attributes () { return this._attributes; } + /** * @en All vertex buffers used by the sub mesh * @zh 使用的所有顶点缓冲区。 */ get vertexBuffers () { return this._vertexBuffers; } + /** * @en Index buffer used by the sub mesh * @zh 使用的索引缓冲区,若未使用则无需指定。 */ get indexBuffer () { return this._indexBuffer; } + /** * @en Indirect buffer used by the sub mesh * @zh 间接绘制缓冲区。 @@ -157,12 +207,12 @@ export class RenderingSubMesh { if (this.subMeshIdx === undefined) { return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } }; } - const mesh = this.mesh!; const index = this.subMeshIdx!; + const { mesh } = this; const index = this.subMeshIdx; const positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION) as unknown as Float32Array; const indices = mesh.readIndices(index) as Uint16Array; const max = new Vec3(); const min = new Vec3(); - const pAttri = this.attributes.find(element => element.name === AttributeName.ATTR_POSITION); + const pAttri = this.attributes.find((element) => element.name === AttributeName.ATTR_POSITION); if (pAttri) { const conut = FormatInfos[pAttri.format].count; if (conut === 2) { @@ -197,27 +247,29 @@ export class RenderingSubMesh { * @zh 扁平化的顶点缓冲区。 */ get flatBuffers () { return this._flatBuffers; } - public genFlatBuffers() { + + public genFlatBuffers () { if (this._flatBuffers.length || !this.mesh || this.subMeshIdx === undefined) { return; } - const mesh = this.mesh; + const { mesh } = this; let idxCount = 0; const prim = mesh.struct.primitives[this.subMeshIdx]; const fbArrayHandle = SubMeshPool.get(this._handle, SubMeshView.FLAT_BUFFER_ARRAY); if (prim.indexView) { idxCount = prim.indexView.count; } - for (const bundleIdx of prim.vertexBundelIndices) { + for (let i = 0; i < prim.vertexBundelIndices.length; i++) { + const bundleIdx = prim.vertexBundelIndices[i]; const vertexBundle = mesh.struct.vertexBundles[bundleIdx]; const vbCount = prim.indexView ? prim.indexView.count : vertexBundle.view.count; const vbStride = vertexBundle.view.stride; const vbSize = vbStride * vbCount; - + const rawBufferSize = prim.indexView ? vertexBundle.view.length : vbSize; const hBuffer = RawBufferPool.alloc(rawBufferSize); const buffer = RawBufferPool.getBuffer(hBuffer); const view = prim.indexView ? new Uint8Array(buffer) : new Uint8Array(rawBufferSize); const hFlatBuffer = FlatBufferPool.alloc(); view.set(mesh.data.subarray(vertexBundle.view.offset, vertexBundle.view.offset + vertexBundle.view.length)); - + if (!prim.indexView) { FlatBufferPool.set(hFlatBuffer, FlatBufferView.STRIDE, vbStride); FlatBufferPool.set(hFlatBuffer, FlatBufferView.AMOUNT, vbCount); @@ -243,7 +295,6 @@ export class RenderingSubMesh { FlatBufferArrayPool.push(fbArrayHandle, hFlatBuffer); this._flatBuffers.push({ stride: vbStride, count: vbCount, buffer: vbView }); } - return this._flatBuffers; } /** @@ -255,14 +306,14 @@ export class RenderingSubMesh { 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.struct; + 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; } let jointFormat: Format; let jointOffset: number; - const device: Device = legacyCC.director.root.device; + const { device } = legacyCC.director.root; for (let i = 0; i < prim.vertexBundelIndices.length; i++) { const bundle = struct.vertexBundles[prim.vertexBundelIndices[i]]; jointOffset = 0; @@ -300,42 +351,10 @@ export class RenderingSubMesh { get iaInfo () { return this._iaInfo; } - public mesh?: Mesh; - public subMeshIdx?: number; - - private _flatBuffers: IFlatBuffer[] = []; - private _jointMappedBuffers?: Buffer[]; - private _jointMappedBufferIndices?: number[]; - private _vertexIdChannel?: { stream: number; index: number; }; - private _geometricInfo?: IGeometricInfo; - - private _vertexBuffers: Buffer[]; - private _attributes: Attribute[]; - private _indexBuffer: Buffer | null = null; - private _indirectBuffer: Buffer | null = null; - private _primitiveMode: PrimitiveMode; - private _iaInfo: InputAssemblerInfo; - private _handle: SubMeshHandle = NULL_HANDLE; - get handle () { return this._handle; } - constructor ( - vertexBuffers: Buffer[], attributes: Attribute[], primitiveMode: PrimitiveMode, - indexBuffer: Buffer | null = null, indirectBuffer: Buffer | null = null, - ) { - this._attributes = attributes; - this._vertexBuffers = vertexBuffers; - this._indexBuffer = indexBuffer; - this._indirectBuffer = indirectBuffer; - this._primitiveMode = primitiveMode; - this._iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer); - this._handle = SubMeshPool.alloc(); - const fbArrayHandle = FlatBufferArrayPool.alloc(); - SubMeshPool.set(this._handle, SubMeshView.FLAT_BUFFER_ARRAY, fbArrayHandle); - } - public destroy () { for (let i = 0; i < this.vertexBuffers.length; i++) { this.vertexBuffers[i].destroy(); @@ -356,7 +375,7 @@ export class RenderingSubMesh { this._indirectBuffer.destroy(); this._indirectBuffer = null; } - if(this._handle) { + if (this._handle) { const fbArrayHandle = SubMeshPool.get(this._handle, SubMeshView.FLAT_BUFFER_ARRAY); freeHandleArray(fbArrayHandle, FlatBufferArrayPool, FlatBufferPool); @@ -391,14 +410,14 @@ export class RenderingSubMesh { } private _allocVertexIdBuffer (device: Device) { - const vertexCount = (this.vertexBuffers.length === 0 || this.vertexBuffers[0].stride === 0) ? - 0 : - // TODO: This depends on how stride of a vertex buffer is defined; Consider padding problem. - this.vertexBuffers[0].size / this.vertexBuffers[0].stride; + const vertexCount = (this.vertexBuffers.length === 0 || this.vertexBuffers[0].stride === 0) + ? 0 + // TODO: This depends on how stride of a vertex buffer is defined; Consider padding problem. + : this.vertexBuffers[0].size / this.vertexBuffers[0].stride; const vertexIds = new Float32Array(vertexCount); for (let iVertex = 0; iVertex < vertexCount; ++iVertex) { - // `+0.5` because on some platforms, the "fetched integer" may have small error. - // For example `26` may yield `25.99999`, which is convert to `25` instead of `26` using `int()`. + // `+0.5` because on some platforms, the "fetched integer" may have small error. + // For example `26` may yield `25.99999`, which is convert to `25` instead of `26` using `int()`. vertexIds[iVertex] = iVertex + 0.5; } @@ -543,7 +562,6 @@ const globalEmptyMeshBuffer = new Uint8Array(); */ @ccclass('cc.Mesh') export class Mesh extends Asset { - get _nativeAsset (): ArrayBuffer { return this._data.buffer; } @@ -607,7 +625,7 @@ export class Mesh extends Asset { * @zh 此网格的哈希值。 */ get hash () { - // hashes should already be computed offline, but if not, make one + // hashes should already be computed offline, but if not, make one if (!this._hash) { this._hash = murmurhash2_32_gc(this._data, 666); } return this._hash; } @@ -629,6 +647,8 @@ export class Mesh extends Asset { return this._renderingSubMeshes!; } + public morphRendering: MorphRendering | null = null; + @serializable private _struct: Mesh.IStruct = { vertexBundles: [], @@ -642,9 +662,13 @@ export class Mesh extends Asset { private _hash = 0; private _data: Uint8Array = globalEmptyMeshBuffer; + private _initialized = false; + private _renderingSubMeshes: RenderingSubMesh[] | null = null; - private _boneSpaceBounds = new Map(); + + private _boneSpaceBounds: Map = new Map(); + private _jointBufferIndices: number[] | null = null; constructor () { @@ -660,12 +684,12 @@ export class Mesh extends Asset { this._initialized = true; if (this._data.byteLength !== this._dataLength) { - // In the case of deferred loading, `this._data` is created before - // the actual binary buffer is loaded. + // In the case of deferred loading, `this._data` is created before + // the actual binary buffer is loaded. this._data = new Uint8Array(this._dataLength); legacyCC.assetManager.postLoadNative(this); } - const buffer = this._data.buffer; + const { buffer } = this._data; const gfxDevice: Device = legacyCC.director.root.device; const vertexBuffers = this._createVertexBuffers(gfxDevice, buffer); const indexBuffers: Buffer[] = []; @@ -709,8 +733,7 @@ export class Mesh extends Asset { } if (this.loaded) { indexBuffer.update(ib); - } - else { + } else { this.once('load', () => { indexBuffer!.update(ib); }); @@ -807,12 +830,12 @@ export class Mesh extends Asset { const bounds: (aabb | null)[] = []; this._boneSpaceBounds.set(skeleton.hash, bounds); const valid: boolean[] = []; - const bindposes = skeleton.bindposes; + const { bindposes } = skeleton; for (let i = 0; i < bindposes.length; i++) { bounds.push(new aabb(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity)); valid.push(false); } - const primitives = this._struct.primitives; + const { primitives } = this._struct; for (let p = 0; p < primitives.length; p++) { const joints = this.readAttribute(p, AttributeName.ATTR_JOINTS); const weights = this.readAttribute(p, AttributeName.ATTR_WEIGHTS); @@ -835,8 +858,7 @@ export class Mesh extends Asset { } for (let i = 0; i < bindposes.length; i++) { const b = bounds[i]!; - if (!valid[i]) { bounds[i] = null; } - else { aabb.fromPoints(b, b.center, b.halfExtents); } + if (!valid[i]) { bounds[i] = null; } else { aabb.fromPoints(b, b.center, b.halfExtents); } } return bounds; } @@ -879,11 +901,12 @@ export class Mesh extends Asset { const vtxBdl = struct.vertexBundles[i]; for (let j = 0; j < vtxBdl.attributes.length; j++) { if (vtxBdl.attributes[j].name === AttributeName.ATTR_POSITION || vtxBdl.attributes[j].name === AttributeName.ATTR_NORMAL) { - const format = vtxBdl.attributes[j].format; + const { format } = vtxBdl.attributes[j]; const inputView = new DataView( data.buffer, - vtxBdl.view.offset + getOffset(vtxBdl.attributes, j)); + vtxBdl.view.offset + getOffset(vtxBdl.attributes, j), + ); const reader = getReader(inputView, format); const writer = getWriter(inputView, format); @@ -900,12 +923,13 @@ export class Mesh extends Asset { const zOffset = yOffset + attrComponentByteLength; vec3_temp.set(reader(xOffset), reader(yOffset), reader(zOffset)); switch (vtxBdl.attributes[j].name) { - case AttributeName.ATTR_POSITION: - vec3_temp.transformMat4(worldMatrix); - break; - case AttributeName.ATTR_NORMAL: - Vec3.transformQuat(vec3_temp, vec3_temp, rotate!); - break; + case AttributeName.ATTR_POSITION: + vec3_temp.transformMat4(worldMatrix); + break; + case AttributeName.ATTR_NORMAL: + Vec3.transformQuat(vec3_temp, vec3_temp, rotate!); + break; + default: } writer(xOffset, vec3_temp.x); writer(yOffset, vec3_temp.y); @@ -980,12 +1004,12 @@ export class Mesh extends Asset { const f32_temp = new Float32Array(vbView.buffer, srcVBOffset, 3); vec3_temp.set(f32_temp[0], f32_temp[1], f32_temp[2]); switch (attr.name) { - case AttributeName.ATTR_POSITION: - vec3_temp.transformMat4(worldMatrix); - break; - case AttributeName.ATTR_NORMAL: - Vec3.transformQuat(vec3_temp, vec3_temp, rotate!); - break; + case AttributeName.ATTR_POSITION: + vec3_temp.transformMat4(worldMatrix); + break; + case AttributeName.ATTR_NORMAL: + Vec3.transformQuat(vec3_temp, vec3_temp, rotate!); + break; } f32_temp[0] = vec3_temp.x; f32_temp[1] = vec3_temp.y; @@ -1098,7 +1122,6 @@ export class Mesh extends Asset { bufferBlob.setNextAlignment(idxStride); bufferBlob.addBuffer(ib); } - } // Create mesh struct. @@ -1202,10 +1225,8 @@ export class Mesh extends Asset { if (dstPrim.indexView === undefined) { return false; } - } else { - if (dstPrim.indexView) { - return false; - } + } else if (dstPrim.indexView) { + return false; } } @@ -1220,19 +1241,20 @@ export class Mesh extends Asset { * @returns Return null if not found or can't read, otherwise, will create a large enough typed array to contain all data of the attribute, * the array type will match the data type of the attribute. */ - public readAttribute (primitiveIndex: number, attributeName: AttributeName): Storage | null { + public readAttribute (primitiveIndex: number, attributeName: AttributeName): TypedArray | null { let result: TypedArray | null = null; this._accessAttribute(primitiveIndex, attributeName, (vertexBundle, iAttribute) => { const vertexCount = vertexBundle.view.count; - const format = vertexBundle.attributes[iAttribute].format; + const { format } = vertexBundle.attributes[iAttribute]; const storageConstructor = getTypedArrayConstructor(FormatInfos[format]); if (vertexCount === 0) { - return new storageConstructor(); + return; } const inputView = new DataView( this._data.buffer, - vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute)); + vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute), + ); const formatInfo = FormatInfos[format]; const reader = getReader(inputView, format); @@ -1248,7 +1270,6 @@ export class Mesh extends Asset { } } result = storage; - return; }); return result; } @@ -1271,11 +1292,12 @@ export class Mesh extends Asset { written = true; return; } - const format = vertexBundle.attributes[iAttribute].format; + const { format } = vertexBundle.attributes[iAttribute]; const inputView = new DataView( this._data.buffer, - vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute)); + vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute), + ); const outputView = new DataView(buffer, offset); @@ -1301,7 +1323,6 @@ export class Mesh extends Asset { } } written = true; - return; }); return written; } @@ -1321,7 +1342,7 @@ export class Mesh extends Asset { if (!primitive.indexView) { return null; } - const stride = primitive.indexView.stride; + const { stride } = primitive.indexView; const ctor = stride === 1 ? Uint8Array : (stride === 2 ? Uint16Array : Uint32Array); return new ctor(this._data.buffer, primitive.indexView.offset, primitive.indexView.count); } @@ -1333,7 +1354,7 @@ export class Mesh extends Asset { * @param outputArray The target output array * @returns Return false if failed to access the indices data, return true otherwise. */ - public copyIndices (primitiveIndex: number, outputArray: number[] | ArrayBufferView) { + public copyIndices (primitiveIndex: number, outputArray: number[] | ArrayBufferView): boolean { if (primitiveIndex >= this._struct.primitives.length) { return false; } @@ -1353,7 +1374,8 @@ export class Mesh extends Asset { private _accessAttribute ( primitiveIndex: number, attributeName: AttributeName, - accessor: (vertexBundle: Mesh.IVertexBundle, iAttribute: number) => void) { + accessor: (vertexBundle: Mesh.IVertexBundle, iAttribute: number) => void, + ) { if (primitiveIndex >= this._struct.primitives.length) { return; } @@ -1367,12 +1389,10 @@ export class Mesh extends Asset { accessor(vertexBundle, iAttribute); break; } - return; } private _createVertexBuffers (gfxDevice: Device, data: ArrayBuffer): Buffer[] { return this._struct.vertexBundles.map((vertexBundle) => { - const vertexBuffer = gfxDevice.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, @@ -1383,8 +1403,7 @@ export class Mesh extends Asset { const view = new Uint8Array(data, vertexBundle.view.offset, vertexBundle.view.length); if (this.loaded) { vertexBuffer.update(view); - } - else { + } else { this.once('load', () => { vertexBuffer.update(view); }); @@ -1392,8 +1411,6 @@ export class Mesh extends Asset { return vertexBuffer; }); } - - public morphRendering: MorphRendering | null = null; } legacyCC.Mesh = Mesh; @@ -1406,7 +1423,7 @@ function getOffset (attributes: Attribute[], attributeIndex: number) { return result; } -const isLittleEndian = sys.isLittleEndian; +const { isLittleEndian } = sys; function getComponentByteLength (format: Format) { const info = FormatInfos[format]; @@ -1418,41 +1435,41 @@ function getReader (dataView: DataView, format: Format) { const stride = info.size / info.count; switch (info.type) { - case FormatType.UNORM: { - switch (stride) { - case 1: return (offset: number) => dataView.getUint8(offset); - case 2: return (offset: number) => dataView.getUint16(offset, isLittleEndian); - case 4: return (offset: number) => dataView.getUint32(offset, isLittleEndian); - } - break; + case FormatType.UNORM: { + switch (stride) { + case 1: return (offset: number) => dataView.getUint8(offset); + case 2: return (offset: number) => dataView.getUint16(offset, isLittleEndian); + case 4: return (offset: number) => dataView.getUint32(offset, isLittleEndian); } - case FormatType.SNORM: { - switch (stride) { - case 1: return (offset: number) => dataView.getInt8(offset); - case 2: return (offset: number) => dataView.getInt16(offset, isLittleEndian); - case 4: return (offset: number) => dataView.getInt32(offset, isLittleEndian); - } - break; + break; + } + case FormatType.SNORM: { + switch (stride) { + case 1: return (offset: number) => dataView.getInt8(offset); + case 2: return (offset: number) => dataView.getInt16(offset, isLittleEndian); + case 4: return (offset: number) => dataView.getInt32(offset, isLittleEndian); } - case FormatType.INT: { - switch (stride) { - case 1: return (offset: number) => dataView.getInt8(offset); - case 2: return (offset: number) => dataView.getInt16(offset, isLittleEndian); - case 4: return (offset: number) => dataView.getInt32(offset, isLittleEndian); - } - break; + break; + } + case FormatType.INT: { + switch (stride) { + case 1: return (offset: number) => dataView.getInt8(offset); + case 2: return (offset: number) => dataView.getInt16(offset, isLittleEndian); + case 4: return (offset: number) => dataView.getInt32(offset, isLittleEndian); } - case FormatType.UINT: { - switch (stride) { - case 1: return (offset: number) => dataView.getUint8(offset); - case 2: return (offset: number) => dataView.getUint16(offset, isLittleEndian); - case 4: return (offset: number) => dataView.getUint32(offset, isLittleEndian); - } - break; - } - case FormatType.FLOAT: { - return (offset: number) => dataView.getFloat32(offset, isLittleEndian); + break; + } + case FormatType.UINT: { + switch (stride) { + case 1: return (offset: number) => dataView.getUint8(offset); + case 2: return (offset: number) => dataView.getUint16(offset, isLittleEndian); + case 4: return (offset: number) => dataView.getUint32(offset, isLittleEndian); } + break; + } + case FormatType.FLOAT: { + return (offset: number) => dataView.getFloat32(offset, isLittleEndian); + } } return null; @@ -1463,41 +1480,41 @@ function getWriter (dataView: DataView, format: Format) { const stride = info.size / info.count; switch (info.type) { - case FormatType.UNORM: { - switch (stride) { - case 1: return (offset: number, value: number) => dataView.setUint8(offset, value); - case 2: return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); - case 4: return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); - } - break; + case FormatType.UNORM: { + switch (stride) { + case 1: return (offset: number, value: number) => dataView.setUint8(offset, value); + case 2: return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); } - case FormatType.SNORM: { - switch (stride) { - case 1: return (offset: number, value: number) => dataView.setInt8(offset, value); - case 2: return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian); - case 4: return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian); - } - break; + break; + } + case FormatType.SNORM: { + switch (stride) { + case 1: return (offset: number, value: number) => dataView.setInt8(offset, value); + case 2: return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian); } - case FormatType.INT: { - switch (stride) { - case 1: return (offset: number, value: number) => dataView.setInt8(offset, value); - case 2: return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian); - case 4: return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian); - } - break; + break; + } + case FormatType.INT: { + switch (stride) { + case 1: return (offset: number, value: number) => dataView.setInt8(offset, value); + case 2: return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian); } - case FormatType.UINT: { - switch (stride) { - case 1: return (offset: number, value: number) => dataView.setUint8(offset, value); - case 2: return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); - case 4: return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); - } - break; - } - case FormatType.FLOAT: { - return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian); + break; + } + case FormatType.UINT: { + switch (stride) { + case 1: return (offset: number, value: number) => dataView.setUint8(offset, value); + case 2: return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case 4: return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); } + break; + } + case FormatType.FLOAT: { + return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian); + } } return null; diff --git a/cocos/core/assets/prefab.ts b/cocos/core/assets/prefab.ts index 0b56adcc52..c3a920812e 100644 --- a/cocos/core/assets/prefab.ts +++ b/cocos/core/assets/prefab.ts @@ -81,7 +81,7 @@ export default class Prefab extends Asset { public static OptimizationPolicy = OptimizationPolicy; public static OptimizationPolicyThreshold = 3; - + /** * @en The main [[Node]] in the prefab * @zh Prefab 中的根节点,[[Node]] 类型 @@ -115,7 +115,7 @@ export default class Prefab extends Asset { */ @serializable @editable - public asyncLoadAssets: Boolean = false; + public asyncLoadAssets = false; // Cache function to optimize instance creation. private _createFunction: Function | null; @@ -140,8 +140,8 @@ export default class Prefab extends Asset { * but you can re-call to refresh the create function once you modified the original prefab data in script. * @zh * 将预制数据动态转换为最小化代码。
-     * 此方法将在第一次实例化预制件之前自动调用,
-     * 但是您可以在脚本中修改原始预制数据后重新调用以刷新创建功能。 + * 此方法将在第一次实例化预制件之前自动调用,
+ * 但是您可以在脚本中修改原始预制数据后重新调用以刷新创建功能。 */ public compileCreateFunction (): void { this._createFunction = compile(this.data); @@ -167,7 +167,7 @@ export default class Prefab extends Asset { private _instantiate () { let node; - let useJit: Boolean = false; + let useJit = false; if (SUPPORT_JIT) { if (this.optimizationPolicy === OptimizationPolicy.SINGLE_INSTANCE) { useJit = false; diff --git a/cocos/core/assets/render-texture.ts b/cocos/core/assets/render-texture.ts index d262f649df..fead1b40ed 100644 --- a/cocos/core/assets/render-texture.ts +++ b/cocos/core/assets/render-texture.ts @@ -60,7 +60,7 @@ const _windowInfo: IRenderWindowInfo = { }; /** - * @en Render texture is a render target for [[Camera]] or [[Canvas]] component, + * @en Render texture is a render target for [[Camera]] or [[Canvas]] component, * the render pipeline will use its [[RenderWindow]] as the target of the rendering process. * @zh 渲染贴图是 [[Camera]] 或 [[Canvas]] 组件的渲染目标对象,渲染管线会使用它的 [[RenderWindow]] 作为渲染的目标窗口。 */ diff --git a/cocos/core/assets/sprite-frame.ts b/cocos/core/assets/sprite-frame.ts index 7959d893b2..d89ad74de2 100644 --- a/cocos/core/assets/sprite-frame.ts +++ b/cocos/core/assets/sprite-frame.ts @@ -480,7 +480,7 @@ export class SpriteFrame extends Asset { protected _capInsets = [0, 0, 0, 0]; protected _atlasUuid: string = ''; - // @ts-ignore + // @ts-expect-error protected _texture: TextureBase | RenderTexture; protected _flipUv = false; diff --git a/cocos/core/components/component.ts b/cocos/core/components/component.ts index 97b2ac8a8c..f279a634ce 100644 --- a/cocos/core/components/component.ts +++ b/cocos/core/components/component.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ -// tslint:disable + /** * @packageDocumentation @@ -46,9 +46,6 @@ import { errorID, warnID, assertID } from '../platform/debug'; import { CompPrefabInfo } from '../utils'; const idGenerator = new IDGenerator('Comp'); -// @ts-ignore -const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; -// @ts-ignore const IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled; const NullNode = null as unknown as Node; @@ -202,7 +199,7 @@ class Component extends CCObject { if (this._sceneGetter) { return this._sceneGetter(); } else { - return this.node.scene!._renderScene!; + return this.node.scene._renderScene!; } } @@ -357,7 +354,7 @@ class Component extends CCObject { public destroy () { if (EDITOR) { - // @ts-ignore + // @ts-expect-error const depend = this.node._getDependComponent(this); if (depend) { errorID(3626, @@ -380,7 +377,7 @@ class Component extends CCObject { // if (EDITOR && !TEST) { - // @ts-ignore + // @ts-expect-error _Scene.AssetsWatcher.stop(this); } @@ -418,7 +415,7 @@ class Component extends CCObject { * this.schedule((dt) => void log(`time: ${dt}`), 1); * ``` */ - public schedule (callback, interval: number = 0, repeat: number = legacyCC.macro.REPEAT_FOREVER, delay: number = 0) { + public schedule (callback, interval = 0, repeat: number = legacyCC.macro.REPEAT_FOREVER, delay = 0) { assertID(callback, 1619); interval = interval || 0; @@ -451,7 +448,7 @@ class Component extends CCObject { * this.scheduleOnce((dt) => void log(`time: ${dt}`), 2); * ``` */ - public scheduleOnce (callback, delay: number = 0) { + public scheduleOnce (callback, delay = 0) { this.schedule(callback, 0, 0, delay); } @@ -642,47 +639,47 @@ class Component extends CCObject { } const proto = Component.prototype; -// @ts-ignore +// @ts-expect-error proto.update = null; -// @ts-ignore +// @ts-expect-error proto.lateUpdate = null; -// @ts-ignore +// @ts-expect-error proto.__preload = null; -// @ts-ignore +// @ts-expect-error proto.onLoad = null; -// @ts-ignore +// @ts-expect-error proto.start = null; -// @ts-ignore +// @ts-expect-error proto.onEnable = null; -// @ts-ignore +// @ts-expect-error proto.onDisable = null; -// @ts-ignore +// @ts-expect-error proto.onDestroy = null; -// @ts-ignore +// @ts-expect-error proto.onFocusInEditor = null; -// @ts-ignore +// @ts-expect-error proto.onLostFocusInEditor = null; -// @ts-ignore +// @ts-expect-error proto.resetInEditor = null; -// @ts-ignore +// @ts-expect-error proto._getLocalBounds = null; -// @ts-ignore +// @ts-expect-error proto.onRestore = null; -// @ts-ignore +// @ts-expect-error Component._requireComponent = null; -// @ts-ignore +// @ts-expect-error Component._executionOrder = 0; if (EDITOR || TEST) { // INHERITABLE STATIC MEMBERS - // @ts-ignore + // @ts-expect-error Component._executeInEditMode = false; - // @ts-ignore + // @ts-expect-error Component._playOnFocus = false; - // @ts-ignore + // @ts-expect-error Component._disallowMultiple = null; - // @ts-ignore + // @ts-expect-error Component._help = ''; // NON-INHERITED STATIC MEMBERS diff --git a/cocos/core/components/missing-script.ts b/cocos/core/components/missing-script.ts index f774c60fb3..f4911b6d28 100644 --- a/cocos/core/components/missing-script.ts +++ b/cocos/core/components/missing-script.ts @@ -80,7 +80,7 @@ export default class MissingScript extends Component { constructor () { super(); if (EDITOR) { - // @ts-ignore + // @ts-expect-error this.compiled = _Scene.Sandbox.compiled; } } diff --git a/cocos/core/components/ui-base/ui-transform.ts b/cocos/core/components/ui-base/ui-transform.ts index 2804e71f18..cca38ccdfb 100644 --- a/cocos/core/components/ui-base/ui-transform.ts +++ b/cocos/core/components/ui-base/ui-transform.ts @@ -88,7 +88,7 @@ export class UITransform extends Component { this._contentSize.set(value); if (EDITOR) { - // @ts-ignore + // @ts-expect-error this.node.emit(SystemEventType.SIZE_CHANGED, clone); } else { this.node.emit(SystemEventType.SIZE_CHANGED); @@ -112,7 +112,7 @@ export class UITransform extends Component { this._contentSize.width = value; if (EDITOR) { - // @ts-ignore + // @ts-expect-error this.node.emit(SystemEventType.SIZE_CHANGED, clone); } else { this.node.emit(SystemEventType.SIZE_CHANGED); @@ -135,7 +135,7 @@ export class UITransform extends Component { this._contentSize.height = value; if (EDITOR) { - // @ts-ignore + // @ts-expect-error this.node.emit(SystemEventType.SIZE_CHANGED, clone); } else { this.node.emit(SystemEventType.SIZE_CHANGED); @@ -310,7 +310,7 @@ export class UITransform extends Component { } if (EDITOR) { - // @ts-ignore + // @ts-expect-error this.node.emit(SystemEventType.SIZE_CHANGED, clone); } else { this.node.emit(SystemEventType.SIZE_CHANGED); @@ -612,7 +612,7 @@ export class UITransform extends Component { } } - // @ts-ignore + // @ts-expect-error parent = parent.parent; } } diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index 499eff4493..0a7888925c 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -29,12 +29,12 @@ * @hidden */ -// tslint:disable:only-arrow-functions -// tslint:disable:prefer-for-of -// tslint:disable:no-shadowed-variable -// tslint:disable:max-line-length -// tslint:disable:jsdoc-format -// tslint:disable:forin + + + + + + import { errorID, warnID } from '../platform/debug'; import * as js from '../utils/js'; @@ -270,8 +270,7 @@ function define (className, baseClass, mixins, options) { renderName = 'render_stage'; } // 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里 - // @ts-ignore - // tslint:disable-next-line:no-unused-expression + window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1); } diff --git a/cocos/core/data/deserialize-dynamic.ts b/cocos/core/data/deserialize-dynamic.ts index 42b8f33fbc..fa1557ffba 100644 --- a/cocos/core/data/deserialize-dynamic.ts +++ b/cocos/core/data/deserialize-dynamic.ts @@ -38,7 +38,7 @@ import * as Attr from './utils/attribute'; import MissingScript from '../components/missing-script'; import { Details } from './deserialize'; -// tslint:disable: no-shadowed-variable + // IMPLEMENT OF DESERIALIZATION @@ -102,7 +102,7 @@ const compileDeserialize = SUPPORT_JIT ? (self, klass) => { ]; const fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); // sources.push('var vb,vn,vs,vo,vu,vf;'); // boolean, number, string, object, undefined, function - // tslint:disable-next-line: prefer-for-of + for (let p = 0; p < props.length; p++) { const propName = props[p]; if ((PREVIEW || (EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) { @@ -203,7 +203,7 @@ const compileDeserialize = SUPPORT_JIT ? (self, klass) => { const DEFAULT = Attr.DELIMETER + 'default'; const FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; - // tslint:disable-next-line: prefer-for-of + for (let p = 0; p < props.length; p++) { const propName = props[p]; let propNameToRead = propName; @@ -359,7 +359,7 @@ function _deserializeFireClass (self, obj, serialized, klass) { // } // } -// tslint:disable-next-line: class-name + class _Deserializer { public static pool: js.Pool<{}>; @@ -446,14 +446,14 @@ class _Deserializer { * @param {Object} [owner] - debug only * @param {String} [propName] - debug only */ - private _deserializeObject (serialized, owner?: Object, propName?: String) { + private _deserializeObject (serialized, owner?: Object, propName?: string) { let prop; let obj: any = null; // the obj to return let klass: any = null; const type = serialized.__type__; if (type === 'TypedArray') { const array = serialized.array; - // @ts-ignore + // @ts-expect-error obj = new window[serialized.ctor](array.length); for (let i = 0; i < array.length; ++i) { obj[i] = array[i]; @@ -473,7 +473,6 @@ class _Deserializer { return null; } const self = this; - // @ts-ignore function deserializeByType () { // instantiate a new object obj = new klass(); @@ -490,7 +489,6 @@ class _Deserializer { } } - // @ts-ignore function checkDeserializeByType () { try { deserializeByType(); @@ -510,7 +508,7 @@ class _Deserializer { deserializeByType(); } } - else if ( !Array.isArray(serialized) ) { + else if (!Array.isArray(serialized)) { // embedded primitive javascript object @@ -614,7 +612,7 @@ class _Deserializer { const DEFAULT = Attr.DELIMETER + 'default'; const attrs = Attr.getClassAttrs(klass); const fastDefinedProps = klass.__props__ || Object.keys(instance); // 遍历 instance,如果具有类型,才不会把 __type__ 也读进来 - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < fastDefinedProps.length; i++) { const propName = fastDefinedProps[i]; let value = serialized[propName]; @@ -646,7 +644,7 @@ _Deserializer.pool = new js.Pool((obj: any) => { obj._idObjList.length = 0; obj._idPropList.length = 0; }, 1); -// @ts-ignore +// @ts-expect-error _Deserializer.pool.get = function (result, classFinder, customEnv, ignoreEditorOnly) { const cache: any = this._get(); if (cache) { @@ -674,7 +672,7 @@ export function deserializeDynamic (data, details: Details, options) { details.init(); - // @ts-ignore + // @ts-expect-error const deserializer: _Deserializer = _Deserializer.pool.get(details, classFinder, customEnv, ignoreEditorOnly); legacyCC.game._isCloning = true; diff --git a/cocos/core/data/deserialize.ts b/cocos/core/data/deserialize.ts index e60f8a014a..11e465a9ee 100644 --- a/cocos/core/data/deserialize.ts +++ b/cocos/core/data/deserialize.ts @@ -99,26 +99,26 @@ function serializeBuiltinValueTypes (obj: ValueType): IValueTypeData | null { const typeId = BuiltinValueTypes.indexOf(ctor); switch (ctor) { case Vec2: - // @ts-ignore + // @ts-expect-error return [typeId, obj.x, obj.y]; case Vec3: - // @ts-ignore + // @ts-expect-error return [typeId, obj.x, obj.y, obj.z]; case Vec4: case Quat: - // @ts-ignore + // @ts-expect-error return [typeId, obj.x, obj.y, obj.z, obj.w]; case Color: - // @ts-ignore + // @ts-expect-error return [typeId, obj._val]; case Size: - // @ts-ignore + // @ts-expect-error return [typeId, obj.width, obj.height]; case Rect: - // @ts-ignore + // @ts-expect-error return [typeId, obj.x, obj.y, obj.width, obj.height]; case Mat4: - // @ts-ignore + // @ts-expect-error const res: IValueTypeData = new Array(1 + 16); res[VALUETYPE_SETTER] = typeId; Mat4.toArray(res, obj as Mat4, 1); @@ -505,7 +505,7 @@ interface ICustomHandler { customEnv: any, } type ClassFinder = { - // tslint:disable-next-line:callable-types + (type: string): AnyCtor; // // for editor // onDereferenced: (curOwner: object, curPropName: string, newOwner: object, newPropName: string) => void; @@ -620,7 +620,7 @@ export function dereference (refs: IRefs, instances: IFileData[File.Instances], // owner is object const instanceOffset: number = refs[dataLength] * Refs.EACH_RECORD_LENGTH; for (; i < instanceOffset; i += Refs.EACH_RECORD_LENGTH) { - const owner = refs[i] as any; + const owner = refs[i] ; const target = instances[refs[i + Refs.TARGET_OFFSET]]; const keyIndex = refs[i + Refs.KEY_OFFSET] as StringIndexBnotNumber; @@ -633,7 +633,7 @@ export function dereference (refs: IRefs, instances: IFileData[File.Instances], } // owner is instance index for (; i < dataLength; i += Refs.EACH_RECORD_LENGTH) { - const owner = instances[refs[i]] as any; + const owner = instances[refs[i]] ; const target = instances[refs[i + Refs.TARGET_OFFSET]]; const keyIndex = refs[i + Refs.KEY_OFFSET] as StringIndexBnotNumber; @@ -762,11 +762,10 @@ function parseArray (data: IFileData, owner: any, key: string, value: IArrayData const array = value[ARRAY_ITEM_VALUES]; owner[key] = array; for (let i = 0; i < array.length; ++i) { - const subValue = array[i] as AnyData; + const subValue = array[i] ; const type = value[i + 1] as DataTypeID; if (type !== DataTypeID.SimpleType) { const op = ASSIGNMENTS[type]; - // @ts-ignore op(data, array, i, subValue); } } @@ -806,7 +805,7 @@ ASSIGNMENTS[DataTypeID.Array] = parseArray; function parseInstances (data: IFileData): RootInstanceIndex { const instances = data[File.Instances]; const instanceTypes = data[File.InstanceTypes]; - const instanceTypesLen = instanceTypes === EMPTY_PLACEHOLDER ? 0 : (instanceTypes as OtherObjectTypeID[]).length; + const instanceTypesLen = instanceTypes === EMPTY_PLACEHOLDER ? 0 : (instanceTypes).length; let rootIndex = instances[instances.length - 1]; let normalObjectCount = instances.length - instanceTypesLen; if (typeof rootIndex !== 'number') { @@ -835,7 +834,7 @@ function parseInstances (data: IFileData): RootInstanceIndex { // class index for DataTypeID.CustomizedClass const ctor = classes[type] as CCClass; // class - instances[insIndex] = deserializeCustomCCObject(data, ctor, eachData as ICustomObjectDataContent); + instances[insIndex] = deserializeCustomCCObject(data, ctor, eachData); } else { @@ -843,7 +842,6 @@ function parseInstances (data: IFileData): RootInstanceIndex { type = (~type) as PrimitiveObjectTypeID; const op = ASSIGNMENTS[type]; - // @ts-ignore op(data, instances, insIndex, eachData); } } @@ -858,7 +856,7 @@ function parseInstances (data: IFileData): RootInstanceIndex { // for (let i = 0; i < keys.length; ++i) { // let newKey = attrs[keys[i] + DESERIALIZE_AS]; // if (newKey) { -// // @ts-ignore +// // @ts-expect-error // if (keys.includes(newKey)) { // // %s cannot be deserialized by property %s because %s was also present in the serialized data. // warnID(, newKey, keys[i], newKey); @@ -924,7 +922,7 @@ function cacheMasks (data: IPackedFileData) { const classes = data[File.SharedClasses]; for (let i = 0; i < masks.length; ++i) { const mask = masks[i]; - // @ts-ignore + // @ts-expect-error mask[MASK_CLASS] = classes[mask[MASK_CLASS]]; } } @@ -962,7 +960,7 @@ function parseResult (data: IFileData) { } const uuid = dependUuids[i]; if (typeof uuid === 'number') { - dependUuids[i] = (dependSharedUuids as SharedString[])[uuid as StringIndex]; + dependUuids[i] = (dependSharedUuids as SharedString[])[uuid ]; } else { // added by Details object directly in _deserialize diff --git a/cocos/core/data/instantiate-jit.ts b/cocos/core/data/instantiate-jit.ts index a7433adb2c..dbfce262ae 100644 --- a/cocos/core/data/instantiate-jit.ts +++ b/cocos/core/data/instantiate-jit.ts @@ -39,9 +39,7 @@ import {flattenCodeArray} from './utils/compiler'; import { TEST } from 'internal:constants'; import { legacyCC } from '../global-exports'; -// @ts-ignore const Destroyed = CCObject.Flags.Destroyed; -// @ts-ignore const PersistentMask = CCObject.Flags.PersistentMask; const DEFAULT = Attr.DELIMETER + 'default'; const IDENTIFIER_RE = CCClass.IDENTIFIER_RE; @@ -139,7 +137,7 @@ class Assignments { else { return; } - // tslint:disable: prefer-for-of + for (let i = 0; i < this._exps.length; i++) { const pair = this._exps[i]; writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + '=', pair[1]); @@ -151,7 +149,7 @@ Assignments.pool = new js.Pool((obj: any) => { obj._exps.length = 0; obj._targetExp = null; }, 1); -// @ts-ignore +// @ts-expect-error Assignments.pool.get = function (targetExpression) { const cache: any = this._get() || new Assignments(); cache._targetExp = targetExpression; @@ -296,8 +294,8 @@ class Parser { } public setValueType (codeArray, defaultValue, srcValue, targetExpression) { - // @ts-ignore - const assignments: any = Assignments.pool.get!(targetExpression); + // @ts-expect-error + const assignments: any = Assignments.pool.get(targetExpression); let fastDefinedProps = defaultValue.constructor.__props__; if (!fastDefinedProps) { fastDefinedProps = Object.keys(defaultValue); @@ -363,7 +361,7 @@ class Parser { } public instantiateTypedArray (value) { - let type = value.constructor.name; + const type = value.constructor.name; if (value.length === 0) { return 'new ' + type; } diff --git a/cocos/core/data/instantiate.ts b/cocos/core/data/instantiate.ts index d5dd6f39e6..92c69dff70 100644 --- a/cocos/core/data/instantiate.ts +++ b/cocos/core/data/instantiate.ts @@ -106,10 +106,10 @@ export function instantiate (original: any, internalForce?: boolean) { let clone; if (original instanceof CCObject) { - // @ts-ignore + // @ts-expect-error if (original._instantiate) { legacyCC.game._isCloning = true; - // @ts-ignore + // @ts-expect-error clone = original._instantiate(); legacyCC.game._isCloning = false; return clone; @@ -175,7 +175,7 @@ function doInstantiate (obj, parent?) { function enumerateCCClass (klass, obj, clone, parent) { const props = klass.__values__; - // tslint:disable: prefer-for-of + for (let p = 0; p < props.length; p++) { const key = props[p]; const value = obj[key]; @@ -246,7 +246,7 @@ function instantiateObj (obj, parent) { if (ArrayBuffer.isView(obj)) { let len = (obj as any).length; clone = new ((obj as any).constructor)(len); - // @ts-ignore + // @ts-expect-error obj._iN$t = clone; objsToClearTmpVar.push(obj); for (let i = 0; i < len; ++i) { @@ -257,7 +257,7 @@ function instantiateObj (obj, parent) { if (Array.isArray(obj)) { const len = obj.length; clone = new Array(len); - // @ts-ignore + // @ts-expect-error obj._iN$t = clone; objsToClearTmpVar.push(obj); for (let i = 0; i < len; ++i) { diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.ts index 5bb96248a8..24b0d21774 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -99,7 +99,7 @@ function compileDestruct (obj, ctor) { if (CCClass._isCCClass(ctor)) { const attrs = legacyCC.Class.Attr.getClassAttrs(ctor); const propList = ctor.__props__; - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < propList.length; i++) { key = propList[i]; const attrKey = key + legacyCC.Class.Attr.DELIMETER + 'default'; @@ -126,7 +126,7 @@ function compileDestruct (obj, ctor) { if (SUPPORT_JIT) { // compile code let func = ''; - // tslint:disable: forin + for (key in propsToReset) { let statement; if (CCClass.IDENTIFIER_RE.test(key)) { @@ -277,7 +277,7 @@ class CCObject { if (EDITOR && deferredDestroyTimer === null && legacyCC.engine && ! legacyCC.engine._isUpdating) { // auto destroy immediate in edit mode - // @ts-ignore + // @ts-expect-error deferredDestroyTimer = setImmediate(CCObject._deferredDestroy); } return true; @@ -320,9 +320,9 @@ class CCObject { return; } // engine internal callback - // @ts-ignore + // @ts-expect-error if (this._onPreDestroy) { - // @ts-ignore + // @ts-expect-error this._onPreDestroy(); } @@ -350,7 +350,7 @@ if (EDITOR || TEST) { * @method realDestroyInEditor * @private */ - // @ts-ignore + // @ts-expect-error prototype.realDestroyInEditor = function () { if ( !(this._objFlags & Destroyed) ) { warnID(5001); @@ -368,7 +368,7 @@ if (EDITOR || TEST) { if (EDITOR) { js.value(CCObject, '_clearDeferredDestroyTimer', () => { if (deferredDestroyTimer !== null) { - // @ts-ignore + // @ts-expect-error clearImmediate(deferredDestroyTimer); deferredDestroyTimer = null; } @@ -381,7 +381,7 @@ if (EDITOR) { * @return {object} the serialized json data object * @private */ - // @ts-ignore + // @ts-expect-error prototype._serialize = null; } @@ -392,14 +392,14 @@ if (EDITOR) { * @param {_Deserializer} ctx * @private */ -// @ts-ignore +// @ts-expect-error prototype._deserialize = null; /* * Called before the object being destroyed. * @method _onPreDestroy * @private */ -// @ts-ignore +// @ts-expect-error prototype._onPreDestroy = null; CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); diff --git a/cocos/core/data/utils/attribute.ts b/cocos/core/data/utils/attribute.ts index 42d3e79988..cac92da010 100644 --- a/cocos/core/data/utils/attribute.ts +++ b/cocos/core/data/utils/attribute.ts @@ -24,8 +24,8 @@ THE SOFTWARE. */ -// tslint:disable:only-arrow-functions -// tslint:disable:one-variable-per-declaration + + import { log, warnID } from '../../platform/debug'; import { formatStr, get, getClassName, isChildClassOf, value } from '../../utils/js'; diff --git a/cocos/core/data/utils/preprocess-class.ts b/cocos/core/data/utils/preprocess-class.ts index 2376b9789a..0487a4346b 100644 --- a/cocos/core/data/utils/preprocess-class.ts +++ b/cocos/core/data/utils/preprocess-class.ts @@ -66,7 +66,7 @@ function parseNotify (val, propName, notify, properties) { const newValue = {}; properties[newKey] = newValue; // 将不能用于get方法中的属性移动到newValue中 - // tslint:disable: forin + for (const attr in SerializableAttrs) { const v = SerializableAttrs[attr]; if (val.hasOwnProperty(attr)) { @@ -157,7 +157,7 @@ function getBaseClassWherePropertyDefined_DEV (propName, cls) { } } -// tslint:disable: no-shadowed-variable + function _wrapOptions (isGetset: boolean, _default, type?: Function | Function[]) { let res: { @@ -244,7 +244,7 @@ export function doValidateMethodWithProps_DEV (func, funcName, className, cls, b js.isChildClassOf(base, legacyCC.Component) && !CALL_SUPER_DESTROY_REG_DEV.test(func) ) { - // tslint:disable-next-line: max-line-length + error(`Overwriting '${funcName}' function in '${className}' class without calling super is not allowed. Call the super function in '${funcName}' please.`); } } diff --git a/cocos/core/data/utils/requiring-frame.ts b/cocos/core/data/utils/requiring-frame.ts index ca188f21d5..09deae3802 100644 --- a/cocos/core/data/utils/requiring-frame.ts +++ b/cocos/core/data/utils/requiring-frame.ts @@ -53,7 +53,7 @@ export function pop () { const module = frameInfo.module; let exports = module.exports; if (exports === frameInfo.exports) { - // tslint:disable-next-line: forin + for (const anykey in exports) { // exported return; diff --git a/cocos/core/default-constants.ts b/cocos/core/default-constants.ts index 856db84e58..d4e20aacd6 100644 --- a/cocos/core/default-constants.ts +++ b/cocos/core/default-constants.ts @@ -19,7 +19,7 @@ export const PREVIEW = tryDefineGlobal('CC_PREVIEW', !EDITOR); export const DEV = tryDefineGlobal('CC_DEV', true); // (CC_EDITOR && !CC_BUILD) || CC_PREVIEW || CC_TEST export const DEBUG = tryDefineGlobal('CC_DEBUG', true); // CC_DEV || Debug Build export const JSB = tryDefineGlobal('CC_JSB', defined('jsb')); -// @ts-ignore +// @ts-expect-error export const WECHAT = tryDefineGlobal('CC_WECHAT', !!(defined('wx') && (wx.getSystemInfoSync || wx.getSharedCanvas))); export const MINIGAME = tryDefineGlobal('CC_MINIGAME', false); export const RUNTIME_BASED = tryDefineGlobal('CC_RUNTIME_BASED', false); @@ -31,5 +31,5 @@ export const COCOSPLAY = tryDefineGlobal('CC_COCOSPLAY', false); export const HUAWEI = tryDefineGlobal('CC_HUAWEI', false); export const OPPO = tryDefineGlobal('CC_OPPO', false); export const VIVO = tryDefineGlobal('CC_VIVO', false); -// @ts-ignore +// @ts-expect-error export const SUPPORT_JIT = tryDefineGlobal('CC_SUPPORT_JIT', ('function' === typeof loadRuntime)); diff --git a/cocos/core/director.ts b/cocos/core/director.ts index df436aa533..ee84bf69db 100644 --- a/cocos/core/director.ts +++ b/cocos/core/director.ts @@ -463,7 +463,7 @@ export class Director extends EventTarget { if (BUILD && DEBUG) { console.time('InitScene'); } - // @ts-ignore + // @ts-expect-error scene._load(); // ensure scene initialized if (BUILD && DEBUG) { console.timeEnd('InitScene'); @@ -529,7 +529,7 @@ export class Director extends EventTarget { if (BUILD && DEBUG) { console.time('Activate'); } - // @ts-ignore + // @ts-expect-error scene._activate(); if (BUILD && DEBUG) { console.timeEnd('Activate'); @@ -561,7 +561,7 @@ export class Director extends EventTarget { assertID(scene instanceof Scene, 1216); // ensure scene initialized - // @ts-ignore + // @ts-expect-error scene._load(); // Delay run / replace scene to the end of the frame @@ -583,7 +583,7 @@ export class Director extends EventTarget { warnID(1208, sceneName, this._loadingScene); return false; } - var bundle = legacyCC.assetManager.bundles.find((bundle) => { + const bundle = legacyCC.assetManager.bundles.find((bundle) => { return bundle.getSceneInfo(sceneName); }); if (bundle) { @@ -638,7 +638,6 @@ export class Director extends EventTarget { * @param onProgress 加载进度回调。 * @param onLoaded 加载回调。 */ - // eslint-disable-next-line @typescript-eslint/unified-signatures public preloadScene (sceneName: string, onProgress: Director.OnLoadSceneProgress, onLoaded: Director.OnSceneLoaded): void; public preloadScene ( @@ -646,7 +645,7 @@ export class Director extends EventTarget { onProgress?: Director.OnLoadSceneProgress | Director.OnSceneLoaded, onLoaded?: Director.OnSceneLoaded) { - var bundle = legacyCC.assetManager.bundles.find(function (bundle) { + const bundle = legacyCC.assetManager.bundles.find(function (bundle) { return bundle.getSceneInfo(sceneName); }); if (bundle) { diff --git a/cocos/core/event/event-target-factory.ts b/cocos/core/event/event-target-factory.ts index 0cf05be209..3cb3954f81 100644 --- a/cocos/core/event/event-target-factory.ts +++ b/cocos/core/event/event-target-factory.ts @@ -34,7 +34,7 @@ export function applyMixins (derivedCtor: any, baseCtors: any[]) { baseCtors.forEach((baseCtor) => { Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => { if (name !== 'constructor') { - // @ts-ignore + // @ts-expect-error Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name)); } }); diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.ts index 3109fb50a7..f1f9252a1e 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.ts @@ -34,8 +34,7 @@ import { CallbacksInvoker } from './callbacks-invoker'; import { legacyCC } from '../global-exports'; import { Eventify } from './eventify'; -// eslint-disable-next-line @typescript-eslint/no-extraneous-class -class Empty {}; +class Empty {} /** * @en diff --git a/cocos/core/game.ts b/cocos/core/game.ts index 0da085977a..29e02151d8 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -198,7 +198,7 @@ export class Game extends EventTarget { * }); * ``` */ - public static EVENT_HIDE: string = 'game_on_hide'; + public static EVENT_HIDE = 'game_on_hide'; /** * @en Event triggered when game back to foreground
@@ -222,7 +222,7 @@ export class Game extends EventTarget { * @en Event triggered after game inited, at this point all engine objects and game scripts are loaded * @zh 游戏启动后的触发事件,此时加载所有的引擎对象和游戏脚本。 */ - public static EVENT_GAME_INITED: string = 'game_inited'; + public static EVENT_GAME_INITED = 'game_inited'; /** * @en Event triggered after engine inited, at this point you will be able to use all engine classes.
@@ -232,7 +232,7 @@ export class Game extends EventTarget { * 它在 cocos creator v1.x 版本中名字为 EVENT_RENDERER_INITED ,在 v2.0 版本中更名为 EVENT_ENGINE_INITED * 并在 cocos creator 3d 版本中将 EVENT_RENDERER_INITED 用作为渲染器初始化的事件。 */ - public static EVENT_ENGINE_INITED: string = 'engine_inited'; + public static EVENT_ENGINE_INITED = 'engine_inited'; /** * @en Event triggered after renderer inited, at this point you will be able to use all gfx renderer feature.
@@ -244,29 +244,29 @@ export class Game extends EventTarget { * @en Event triggered when game restart * @zh 调用restart后,触发事件 */ - public static EVENT_RESTART: string = 'game_on_restart'; + public static EVENT_RESTART = 'game_on_restart'; /** * @en Web Canvas 2d API as renderer backend. * @zh 使用 Web Canvas 2d API 作为渲染器后端。 */ - public static RENDER_TYPE_CANVAS: number = 0; + public static RENDER_TYPE_CANVAS = 0; /** * @en WebGL API as renderer backend. * @zh 使用 WebGL API 作为渲染器后端。 */ - public static RENDER_TYPE_WEBGL: number = 1; + public static RENDER_TYPE_WEBGL = 1; /** * @en OpenGL API as renderer backend. * @zh 使用 OpenGL API 作为渲染器后端。 */ - public static RENDER_TYPE_OPENGL: number = 2; + public static RENDER_TYPE_OPENGL = 2; /** * @en The outer frame of the game canvas; parent of game container. * @zh 游戏画布的外框,container 的父容器。 */ - public frame: Object | null = null; + public frame: Record | null = null; /** * @en The container of game canvas. * @zh 游戏画布的容器。 @@ -282,7 +282,7 @@ export class Game extends EventTarget { * @en The renderer backend of the game. * @zh 游戏的渲染器类型。 */ - public renderType: number = -1; + public renderType = -1; public eventTargetOn = super.on; public eventTargetOnce = super.once; @@ -319,11 +319,11 @@ export class Game extends EventTarget { public _persistRootNodes = {}; // states - public _paused: boolean = true; // whether the game is paused - public _configLoaded: boolean = false; // whether config loaded - public _isCloning: boolean = false; // deserializing or instantiating - public _inited: boolean = false; // whether the engine has inited - public _rendererInitialized: boolean = false; + public _paused = true; // whether the game is paused + public _configLoaded = false; // whether config loaded + public _isCloning = false; // deserializing or instantiating + public _inited = false; // whether the engine has inited + public _rendererInitialized = false; public _gfxDevice: Device | null = null; @@ -430,9 +430,9 @@ export class Game extends EventTarget { */ public restart (): Promise { const afterDrawPromise = new Promise((resolve) => - legacyCC.director.once(legacyCC.Director.EVENT_AFTER_DRAW, () => resolve())); + legacyCC.director.once(legacyCC.Director.EVENT_AFTER_DRAW, () => resolve()) as void); return afterDrawPromise.then(() => { - // tslint:disable-next-line: forin + for (const id in this._persistRootNodes) { this.removePersistRootNode(this._persistRootNodes[id]); } @@ -499,7 +499,7 @@ export class Game extends EventTarget { * The callback is ignored if it is a duplicate (the callbacks are unique). * @param target - The target (this object) to invoke the callback, can be null */ - // @ts-ignore + // @ts-expect-error public once (type: string, callback: Function, target?: object) { // Make sure EVENT_ENGINE_INITED callbacks to be invoked if (this._inited && type === Game.EVENT_ENGINE_INITED) { @@ -526,7 +526,7 @@ export class Game extends EventTarget { if (!EDITOR) { this._initEvents(); } - + legacyCC.director.root.dataPoolManager.jointTexturePool.registerCustomTextureLayouts(config.customJointTextureLayouts); return this._inited; }); @@ -557,7 +557,7 @@ export class Game extends EventTarget { return Promise.resolve(initPromise).then(() => { this._setAnimFrame(); this._runMainLoop(); - + // register system events if (!EDITOR && game.config.registerSystemEvent) { inputManager.registerSystemEvent(game.canvas); @@ -647,7 +647,7 @@ export class Game extends EventTarget { const frameRate = this.config.frameRate; this._frameTime = 1000 / frameRate; if (JSB || RUNTIME_BASED) { - // @ts-ignore + // @ts-expect-error jsb.setPreferredFramesPerSecond(frameRate); window.rAF = window.requestAnimationFrame; window.cAF = window.cancelAnimationFrame; @@ -664,7 +664,7 @@ export class Game extends EventTarget { window.oRequestAnimationFrame || window.msRequestAnimationFrame; if (frameRate !== 60 && frameRate !== 30) { - // @ts-ignore + // @ts-expect-error window.rAF = rAF ? this._stTimeWithRAF : this._stTime; window.cAF = this._ctTime; } @@ -714,7 +714,7 @@ export class Game extends EventTarget { } const config = this.config; const director = legacyCC.director; - let skip: boolean = true; + let skip = true; const frameRate = config.frameRate; debug.setDisplayStats(!!config.showFPS); @@ -849,7 +849,7 @@ export class Game extends EventTarget { ); for (let i = 0; i < ctors.length; i++) { this._gfxDevice = new ctors[i](); - if (this._gfxDevice!.initialize(opts)) { break; } + if (this._gfxDevice.initialize(opts)) { break; } } } @@ -904,12 +904,12 @@ export class Game extends EventTarget { 'webkitvisibilitychange', 'qbrowserVisibilityChange', ]; - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < changeList.length; i++) { document.addEventListener(changeList[i], (event) => { let visible = document[hiddenPropName]; // QQ App - // @ts-ignore + // @ts-expect-error visible = visible || event.hidden; if (visible) { onHidden(); diff --git a/cocos/core/geometry/aabb.ts b/cocos/core/geometry/aabb.ts index 10fe4a05c4..5f882682d1 100644 --- a/cocos/core/geometry/aabb.ts +++ b/cocos/core/geometry/aabb.ts @@ -28,7 +28,7 @@ const transform_extent_m4 = (out: Vec3, extent: Vec3, m4: Mat4) => { * @zh * 基础几何 轴对齐包围盒,使用中心点和半长宽高的结构。 */ -// tslint:disable-next-line: class-name + export default class aabb { /** diff --git a/cocos/core/geometry/frustum.ts b/cocos/core/geometry/frustum.ts index c4cc99f4a5..914cbae772 100644 --- a/cocos/core/geometry/frustum.ts +++ b/cocos/core/geometry/frustum.ts @@ -24,7 +24,7 @@ _v[7] = new Vec3(1, -1, -1); * @zh * 基础几何 截头锥体。 */ -// tslint:disable-next-line: class-name + export class frustum { /** diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index 02852e8d7d..c5e5994dbd 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -21,10 +21,10 @@ import { IRaySubMeshOptions, ERaycastMode, IRaySubMeshResult, IRayMeshOptions, I import { IVec3Like } from '../math/type-define'; import { scene } from '../renderer'; -// tslint:disable:only-arrow-functions -// tslint:disable:one-variable-per-declaration -// tslint:disable:prefer-for-of -// tslint:disable:no-shadowed-variable + + + + /** * @en @@ -408,7 +408,7 @@ const ray_subMesh = (function () { const max = submesh.geometricInfo.boundingBox.max; if (ray_aabb2(ray, min, max)) { const pm = submesh.primitiveMode; - const { positions: vb, indices: ib } = submesh.geometricInfo!; + const { positions: vb, indices: ib } = submesh.geometricInfo; narrowphase(vb, ib!, pm, ray, opt); } return minDis; @@ -1079,7 +1079,7 @@ const obb_obb = (function () { }; })(); -// tslint:disable-next-line: max-line-length + // https://github.com/diku-dk/bvh-tvcg18/blob/1fd3348c17bc8cf3da0b4ae60fdb8f2aa90a6ff0/FOUNDATION/GEOMETRY/GEOMETRY/include/overlap/geometry_overlap_obb_capsule.h /** * @en diff --git a/cocos/core/geometry/line.ts b/cocos/core/geometry/line.ts index 5ec106d6ac..82d75837e0 100644 --- a/cocos/core/geometry/line.ts +++ b/cocos/core/geometry/line.ts @@ -12,7 +12,7 @@ import enums from './enums'; * @zh * 基础几何 line。 */ -// tslint:disable-next-line:class-name + export default class line { /** diff --git a/cocos/core/geometry/obb.ts b/cocos/core/geometry/obb.ts index 375c2f5d07..c522109498 100644 --- a/cocos/core/geometry/obb.ts +++ b/cocos/core/geometry/obb.ts @@ -24,7 +24,7 @@ const transform_extent_m3 = (out: Vec3, extent: Vec3, m3: Mat3) => { * @zh * 基础几何 方向包围盒。 */ -// tslint:disable-next-line:class-name + export default class obb { /** diff --git a/cocos/core/geometry/plane.ts b/cocos/core/geometry/plane.ts index 7523732b05..d7000bd7e9 100644 --- a/cocos/core/geometry/plane.ts +++ b/cocos/core/geometry/plane.ts @@ -18,7 +18,7 @@ const temp_vec4 = legacyCC.v4(); * @zh * 基础几何 plane。 */ -// tslint:disable-next-line:class-name + export default class plane { /** diff --git a/cocos/core/geometry/ray.ts b/cocos/core/geometry/ray.ts index 999888fbd4..f3f7550590 100644 --- a/cocos/core/geometry/ray.ts +++ b/cocos/core/geometry/ray.ts @@ -13,7 +13,7 @@ import { IVec3Like } from '../math/type-define'; * @zh * 基础几何 射线。 */ -// tslint:disable-next-line:class-name + export default class ray { /** @@ -29,7 +29,7 @@ export default class ray { * @param {number} dz 方向的 z 部分。 * @return {ray} 射线。 */ - public static create (ox: number = 0, oy: number = 0, oz: number = 0, dx: number = 0, dy: number = 0, dz: number = 1): ray { + public static create (ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = 1): ray { return new ray(ox, oy, oz, dx, dy, dz); } @@ -145,8 +145,8 @@ export default class ray { * @param {number} dy 方向的 y 部分。 * @param {number} dz 方向的 z 部分。 */ - constructor (ox: number = 0, oy: number = 0, oz: number = 0, - dx: number = 0, dy: number = 0, dz: number = -1) { + constructor (ox = 0, oy = 0, oz = 0, + dx = 0, dy = 0, dz = -1) { this._type = enums.SHAPE_RAY; this.o = new Vec3(ox, oy, oz); this.d = new Vec3(dx, dy, dz); diff --git a/cocos/core/geometry/sphere.ts b/cocos/core/geometry/sphere.ts index 6674a67d9c..85ebdc86b1 100644 --- a/cocos/core/geometry/sphere.ts +++ b/cocos/core/geometry/sphere.ts @@ -20,7 +20,7 @@ function maxComponent (v: Vec3) { return Math.max(Math.max(v.x, v.y), v.z); } * @zh * 基础几何 轴对齐球。 */ -// tslint:disable-next-line: class-name + export default class sphere { /** @@ -201,7 +201,7 @@ export default class sphere { * @param cz 该球的世界坐标的 Z 坐标。 * @param {number} r 半径。 */ - constructor (cx: number = 0, cy: number = 0, cz: number = 0, r: number = 1) { + constructor (cx = 0, cy = 0, cz = 0, r = 1) { this._type = enums.SHAPE_SPHERE; this._center = new Vec3(cx, cy, cz); this._poolHandle = SpherePool.alloc(); diff --git a/cocos/core/geometry/triangle.ts b/cocos/core/geometry/triangle.ts index 6b2b6e9fbe..feefa32535 100644 --- a/cocos/core/geometry/triangle.ts +++ b/cocos/core/geometry/triangle.ts @@ -12,7 +12,7 @@ import enums from './enums'; * @zh * 基础几何 三角形。 */ -// tslint:disable-next-line:class-name + export default class triangle { /** @@ -31,9 +31,9 @@ export default class triangle { * @param {number} cz c 点的 z 部分。 * @return {triangle} 一个新的 triangle。 */ - public static create (ax: number = 1, ay: number = 0, az: number = 0, - bx: number = 0, by: number = 0, bz: number = 0, - cx: number = 0, cy: number = 0, cz: number = 1): triangle { + public static create (ax = 1, ay = 0, az = 0, + bx = 0, by = 0, bz = 0, + cx = 0, cy = 0, cz = 1): triangle { return new triangle(ax, ay, az, bx, by, bz, cx, cy, cz); } @@ -176,9 +176,9 @@ export default class triangle { * @param {number} cy c 点的 y 部分。 * @param {number} cz c 点的 z 部分。 */ - constructor (ax: number = 0, ay: number = 0, az: number = 0, - bx: number = 1, by: number = 0, bz: number = 0, - cx: number = 0, cy: number = 1, cz: number = 0) { + constructor (ax = 0, ay = 0, az = 0, + bx = 1, by = 0, bz = 0, + cx = 0, cy = 1, cz = 0) { this._type = enums.SHAPE_TRIANGLE; this.a = new Vec3(ax, ay, az); this.b = new Vec3(bx, by, bz); diff --git a/cocos/core/gfx/buffer.ts b/cocos/core/gfx/buffer.ts index 98fdfd556b..9efd000c7a 100644 --- a/cocos/core/gfx/buffer.ts +++ b/cocos/core/gfx/buffer.ts @@ -3,6 +3,7 @@ * @module gfx */ +import { Device } from './device'; import { BufferFlagBit, BufferFlags, @@ -13,10 +14,9 @@ import { Obj, ObjectType, } from './define'; -import { Device } from './device'; export class DrawInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public vertexCount: number = 0, @@ -29,10 +29,10 @@ export class DrawInfo { ) {} } -export const DRAW_INFO_SIZE: number = 28; +export const DRAW_INFO_SIZE = 28; export class IndirectBuffer { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public drawInfos: DrawInfo[] = [], @@ -42,7 +42,7 @@ export class IndirectBuffer { export type BufferSource = ArrayBuffer | IndirectBuffer; export class BufferInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public usage: BufferUsage, @@ -54,7 +54,7 @@ export class BufferInfo { } export class BufferViewInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public buffer: Buffer, @@ -124,9 +124,9 @@ export abstract class Buffer extends Obj { protected _device: Device; protected _usage: BufferUsage = BufferUsageBit.NONE; protected _memUsage: MemoryUsage = MemoryUsageBit.NONE; - protected _size: number = 0; - protected _stride: number = 1; - protected _count: number = 0; + protected _size = 0; + protected _stride = 1; + protected _count = 0; protected _flags: BufferFlags = BufferFlagBit.NONE; protected _bakcupBuffer: Uint8Array | null = null; protected _indirectBuffer: IndirectBuffer | null = null; diff --git a/cocos/core/gfx/command-buffer.ts b/cocos/core/gfx/command-buffer.ts index f5cb65bccb..9468a391e8 100644 --- a/cocos/core/gfx/command-buffer.ts +++ b/cocos/core/gfx/command-buffer.ts @@ -3,25 +3,25 @@ * @module gfx */ -import { DescriptorSet } from './descriptor-set'; import { Buffer } from './buffer'; +import { DescriptorSet } from './descriptor-set'; +import { Device } from './device'; +import { Framebuffer } from './framebuffer'; +import { InputAssembler } from './input-assembler'; +import { PipelineState } from './pipeline-state'; +import { Queue } from './queue'; +import { RenderPass } from './render-pass'; +import { Texture } from './texture'; +import { BufferTextureCopy, Color, Rect, Viewport } from './define-class'; import { CommandBufferType, Obj, ObjectType, StencilFace, } from './define'; -import { BufferTextureCopy, Color, Rect, Viewport } from './define-class'; -import { Device } from './device'; -import { Framebuffer } from './framebuffer'; -import { InputAssembler } from './input-assembler'; -import { PipelineState } from './pipeline-state'; -import { Texture } from './texture'; -import { RenderPass } from './render-pass'; -import { Queue } from './queue'; export class CommandBufferInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public queue: Queue, @@ -33,7 +33,7 @@ export class CommandBufferInfo { * @en GFX command buffer. * @zh GFX 命令缓冲。 */ -// tslint:disable: max-line-length + export abstract class CommandBuffer extends Obj { /** @@ -122,7 +122,8 @@ export abstract class CommandBuffer extends Obj { * @param clearDepth The clearing depth. * @param clearStencil The clearing stencil. */ - public abstract beginRenderPass (renderPass: RenderPass, framebuffer: Framebuffer, renderArea: Rect, clearColors: Color[], clearDepth: number, clearStencil: number): void; + public abstract beginRenderPass (renderPass: RenderPass, framebuffer: Framebuffer, + renderArea: Rect, clearColors: Color[], clearDepth: number, clearStencil: number): void; /** * @en End render pass. diff --git a/cocos/core/gfx/define-class.ts b/cocos/core/gfx/define-class.ts index 604e0155e1..cc670146ef 100644 --- a/cocos/core/gfx/define-class.ts +++ b/cocos/core/gfx/define-class.ts @@ -3,7 +3,7 @@ */ export class Rect { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public x: number = 0, @@ -14,7 +14,7 @@ export class Rect { } export class Viewport { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public left: number = 0, @@ -27,7 +27,7 @@ export class Viewport { } export class Color { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public x: number = 0, @@ -38,7 +38,7 @@ export class Color { } export class Offset { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public x: number = 0, @@ -48,7 +48,7 @@ export class Offset { } export class Extent { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public width: number = 0, @@ -58,7 +58,7 @@ export class Extent { } export class TextureSubres { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public mipLevel: number = 0, @@ -68,7 +68,7 @@ export class TextureSubres { } export class TextureCopy { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public srcSubres = new TextureSubres(), @@ -80,7 +80,7 @@ export class TextureCopy { } export class BufferTextureCopy { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public buffStride: number = 0, diff --git a/cocos/core/gfx/define.ts b/cocos/core/gfx/define.ts index 1a51c891ec..07a3bd33ce 100644 --- a/cocos/core/gfx/define.ts +++ b/cocos/core/gfx/define.ts @@ -600,7 +600,7 @@ export enum Feature { } export class FormatInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public readonly name: string, @@ -615,7 +615,7 @@ export class FormatInfo { } export class MemoryStatus { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public bufferSize: number = 0, diff --git a/cocos/core/gfx/descriptor-set-layout.ts b/cocos/core/gfx/descriptor-set-layout.ts index b8d1719065..96bc9fc8f8 100644 --- a/cocos/core/gfx/descriptor-set-layout.ts +++ b/cocos/core/gfx/descriptor-set-layout.ts @@ -3,12 +3,12 @@ * @module gfx */ -import { DescriptorType, Obj, ObjectType, ShaderStageFlagBit, ShaderStageFlags } from './define'; import { Device } from './device'; import { Sampler } from './sampler'; +import { DescriptorType, Obj, ObjectType, ShaderStageFlagBit, ShaderStageFlags } from './define'; export class DescriptorSetLayoutBinding { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public binding: number = -1, @@ -20,7 +20,7 @@ export class DescriptorSetLayoutBinding { } export class DescriptorSetLayoutInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public bindings: DescriptorSetLayoutBinding[] = [] diff --git a/cocos/core/gfx/descriptor-set.ts b/cocos/core/gfx/descriptor-set.ts index c81d24a2ad..9f81c22ac5 100644 --- a/cocos/core/gfx/descriptor-set.ts +++ b/cocos/core/gfx/descriptor-set.ts @@ -4,11 +4,11 @@ */ import { Buffer } from './buffer'; -import { DescriptorType, Obj, ObjectType } from './define'; +import { DescriptorSetLayout } from './descriptor-set-layout'; import { Device } from './device'; import { Sampler } from './sampler'; import { Texture } from './texture'; -import { DescriptorSetLayout } from './descriptor-set-layout'; +import { DescriptorType, Obj, ObjectType } from './define'; export const DESCRIPTOR_BUFFER_TYPE = DescriptorType.UNIFORM_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER | @@ -17,7 +17,7 @@ export const DESCRIPTOR_BUFFER_TYPE = export const DESCRIPTOR_SAMPLER_TYPE = DescriptorType.SAMPLER; export class DescriptorSetInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public layout: DescriptorSetLayout, @@ -62,7 +62,7 @@ export abstract class DescriptorSet extends Obj { */ public bindBuffer (binding: number, buffer: Buffer, index = 0) { const bindingIndex = this._layout!.bindingIndices[binding]; - const info = this._layout!.bindings[bindingIndex]; if (!info) return; + const info = this._layout!.bindings[bindingIndex]; if (!info) { return; } if (info.descriptorType & DESCRIPTOR_BUFFER_TYPE) { const descriptorIndex = this._layout!.descriptorIndices[binding]; if (this._buffers[descriptorIndex + index] !== buffer) { @@ -82,7 +82,7 @@ export abstract class DescriptorSet extends Obj { */ public bindSampler (binding: number, sampler: Sampler, index = 0) { const bindingIndex = this._layout!.bindingIndices[binding]; - const info = this._layout!.bindings[bindingIndex]; if (!info) return; + const info = this._layout!.bindings[bindingIndex]; if (!info) { return; } if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) { const descriptorIndex = this._layout!.descriptorIndices[binding]; if (this._samplers[descriptorIndex + index] !== sampler) { @@ -102,7 +102,7 @@ export abstract class DescriptorSet extends Obj { */ public bindTexture (binding: number, texture: Texture, index = 0) { const bindingIndex = this._layout!.bindingIndices[binding]; - const info = this._layout!.bindings[bindingIndex]; if (!info) return; + const info = this._layout!.bindings[bindingIndex]; if (!info) { return; } if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) { const descriptorIndex = this._layout!.descriptorIndices[binding]; if (this._textures[descriptorIndex + index] !== texture) { diff --git a/cocos/core/gfx/device.ts b/cocos/core/gfx/device.ts index 7d19ec8e98..73f6bd72bf 100644 --- a/cocos/core/gfx/device.ts +++ b/cocos/core/gfx/device.ts @@ -4,11 +4,12 @@ */ import { ccenum } from '../value-types/enum'; -import { DescriptorSet, DescriptorSetInfo } from './descriptor-set'; +import { gfx } from '../../../exports/base'; +import { API, Feature, Filter, Format, MemoryStatus, SurfaceTransform } from './define'; import { Buffer, BufferInfo, BufferViewInfo } from './buffer'; -import { CommandBuffer, CommandBufferInfo } from './command-buffer'; -import { Filter, Format, MemoryStatus, API, Feature, SurfaceTransform } from './define'; import { BufferTextureCopy, Rect } from './define-class'; +import { CommandBuffer, CommandBufferInfo } from './command-buffer'; +import { DescriptorSet, DescriptorSetInfo } from './descriptor-set'; import { Fence, FenceInfo } from './fence'; import { Framebuffer, FramebufferInfo } from './framebuffer'; import { InputAssembler, InputAssemblerInfo } from './input-assembler'; @@ -18,12 +19,11 @@ import { RenderPass, RenderPassInfo } from './render-pass'; import { Sampler, SamplerInfo } from './sampler'; import { Shader, ShaderInfo } from './shader'; import { Texture, TextureInfo, TextureViewInfo } from './texture'; -import { gfx } from '../../../exports/base'; ccenum(Format); export class BindingMappingInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public bufferOffsets: number[] = [], @@ -33,7 +33,7 @@ export class BindingMappingInfo { } export class DeviceInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public canvasElm: HTMLElement, @@ -345,38 +345,38 @@ export abstract class Device { protected _canvas: HTMLCanvasElement | null = null; protected _canvas2D: HTMLCanvasElement | null = null; - protected _gfxAPI: API = API.UNKNOWN; - protected _transform: SurfaceTransform = SurfaceTransform.IDENTITY; - protected _deviceName: string = ''; - protected _renderer: string = ''; - protected _vendor: string = ''; - protected _version: string = ''; - protected _features: boolean[] = new Array(Feature.COUNT); + protected _gfxAPI = API.UNKNOWN; + protected _transform = SurfaceTransform.IDENTITY; + protected _deviceName = ''; + protected _renderer = ''; + protected _vendor = ''; + protected _version = ''; + protected _features = new Array(Feature.COUNT); protected _queue: Queue | null = null; protected _cmdBuff: CommandBuffer | null = null; - protected _devicePixelRatio: number = 1.0; - protected _width: number = 0; - protected _height: number = 0; - protected _nativeWidth: number = 0; - protected _nativeHeight: number = 0; - protected _maxVertexAttributes: number = 0; - protected _maxVertexUniformVectors: number = 0; - protected _maxFragmentUniformVectors: number = 0; - protected _maxTextureUnits: number = 0; - protected _maxVertexTextureUnits: number = 0; - protected _maxUniformBufferBindings: number = 0; - protected _maxUniformBlockSize: number = 0; - protected _maxTextureSize: number = 0; - protected _maxCubeMapTextureSize: number = 0; - protected _uboOffsetAlignment: number = 1; - protected _depthBits: number = 0; - protected _stencilBits: number = 0; - protected _colorFmt: Format = Format.UNKNOWN; - protected _depthStencilFmt: Format = Format.UNKNOWN; - protected _macros: Map = new Map(); - protected _numDrawCalls: number = 0; - protected _numInstances: number = 0; - protected _numTris: number = 0; + protected _devicePixelRatio = 1.0; + protected _width = 0; + protected _height = 0; + protected _nativeWidth = 0; + protected _nativeHeight = 0; + protected _maxVertexAttributes = 0; + protected _maxVertexUniformVectors = 0; + protected _maxFragmentUniformVectors = 0; + protected _maxTextureUnits = 0; + protected _maxVertexTextureUnits = 0; + protected _maxUniformBufferBindings = 0; + protected _maxUniformBlockSize = 0; + protected _maxTextureSize = 0; + protected _maxCubeMapTextureSize = 0; + protected _uboOffsetAlignment = 1; + protected _depthBits = 0; + protected _stencilBits = 0; + protected _colorFmt = Format.UNKNOWN; + protected _depthStencilFmt = Format.UNKNOWN; + protected _macros = new Map(); + protected _numDrawCalls = 0; + protected _numInstances = 0; + protected _numTris = 0; protected _memoryStatus = new MemoryStatus(); protected _clipSpaceMinZ = -1; protected _screenSpaceSignY = 1; diff --git a/cocos/core/gfx/fence.ts b/cocos/core/gfx/fence.ts index 1393f7a8b4..db3bb129d4 100644 --- a/cocos/core/gfx/fence.ts +++ b/cocos/core/gfx/fence.ts @@ -3,14 +3,14 @@ * @module gfx */ -import { Obj, ObjectType } from './define'; import { Device } from './device'; +import { Obj, ObjectType } from './define'; export class FenceInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( - ){} + ) {} } /** diff --git a/cocos/core/gfx/framebuffer.ts b/cocos/core/gfx/framebuffer.ts index bb373cb91b..158f17ad7a 100644 --- a/cocos/core/gfx/framebuffer.ts +++ b/cocos/core/gfx/framebuffer.ts @@ -3,13 +3,13 @@ * @module gfx */ -import { Obj, ObjectType } from './define'; import { Device } from './device'; import { RenderPass } from './render-pass'; import { Texture } from './texture'; +import { Obj, ObjectType } from './define'; export class FramebufferInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public renderPass: RenderPass, diff --git a/cocos/core/gfx/index.ts b/cocos/core/gfx/index.ts index 77a4898126..a42e264729 100644 --- a/cocos/core/gfx/index.ts +++ b/cocos/core/gfx/index.ts @@ -3,8 +3,8 @@ * @module gfx */ -import { polyfillCC } from './polyfill-legacy-cc'; import { legacyCC } from '../global-exports'; +import { polyfillCC } from './polyfill-legacy-cc'; import './deprecated-3.0.0'; export * from './descriptor-set'; diff --git a/cocos/core/gfx/input-assembler.ts b/cocos/core/gfx/input-assembler.ts index ef7bfdf9f4..1214ed6d99 100644 --- a/cocos/core/gfx/input-assembler.ts +++ b/cocos/core/gfx/input-assembler.ts @@ -4,9 +4,9 @@ */ import { Buffer } from './buffer'; -import { Format, Obj, ObjectType } from './define'; import { Device } from './device'; import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; +import { Format, Obj, ObjectType } from './define'; export interface IAttribute { name: string; @@ -18,7 +18,7 @@ export interface IAttribute { } export class Attribute { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public name: string = '', @@ -31,7 +31,7 @@ export class Attribute { } export class InputAssemblerInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public attributes: Attribute[] = [], @@ -179,21 +179,21 @@ export abstract class InputAssembler extends Obj { protected _indexBuffer: Buffer | null = null; - protected _vertexCount: number = 0; + protected _vertexCount = 0; - protected _firstVertex: number = 0; + protected _firstVertex = 0; - protected _indexCount: number = 0; + protected _indexCount = 0; - protected _firstIndex: number = 0; + protected _firstIndex = 0; - protected _vertexOffset: number = 0; + protected _vertexOffset = 0; - protected _instanceCount: number = 0; + protected _instanceCount = 0; - protected _firstInstance: number = 0; + protected _firstInstance = 0; - protected _attributesHash: number = 0; + protected _attributesHash = 0; protected _indirectBuffer: Buffer | null = null; @@ -202,15 +202,12 @@ export abstract class InputAssembler extends Obj { this._device = device; } - public abstract initialize (info: InputAssemblerInfo): boolean; - public abstract destroy (): void; - /** * @en Get the specified vertex buffer. * @zh 获取顶点缓冲。 * @param stream The stream index of the vertex buffer. */ - public getVertexBuffer (stream: number = 0): Buffer | null { + public getVertexBuffer (stream = 0): Buffer | null { if (stream < this._vertexBuffers.length) { return this._vertexBuffers[stream]; } else { @@ -226,4 +223,7 @@ export abstract class InputAssembler extends Obj { } return murmurhash2_32_gc(res, 666); } + + public abstract initialize (info: InputAssemblerInfo): boolean; + public abstract destroy (): void; } diff --git a/cocos/core/gfx/pipeline-layout.ts b/cocos/core/gfx/pipeline-layout.ts index 709d40da81..7f14538fff 100644 --- a/cocos/core/gfx/pipeline-layout.ts +++ b/cocos/core/gfx/pipeline-layout.ts @@ -3,12 +3,12 @@ * @module gfx */ -import { Obj, ObjectType } from './define'; -import { Device } from './device'; import { DescriptorSetLayout } from './descriptor-set-layout'; +import { Device } from './device'; +import { Obj, ObjectType } from './define'; export class PipelineLayoutInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public setLayouts: DescriptorSetLayout[] = [], diff --git a/cocos/core/gfx/pipeline-state.jsb.ts b/cocos/core/gfx/pipeline-state.jsb.ts index d22e84f0bb..bdeed4304e 100644 --- a/cocos/core/gfx/pipeline-state.jsb.ts +++ b/cocos/core/gfx/pipeline-state.jsb.ts @@ -2,6 +2,7 @@ declare const gfx: any; declare type RecursivePartial = { [P in keyof T]?: + T[P] extends Array ? Array> : T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; }; @@ -17,8 +18,9 @@ import { StencilOp, } from './define'; import { Color } from './define-class'; -import { BlendTargetArrayPool, NULL_HANDLE, BlendTargetArrayHandle, RasterizerStateHandle, RasterizerStatePool, RasterizerStateView, - DepthStencilStateHandle, DepthStencilStatePool, DepthStencilStateView, BlendTargetHandle, BlendTargetPool, BlendTargetView, BlendStateHandle, BlendStatePool, BlendStateView } from '../renderer/core/memory-pools'; +import { BlendTargetArrayPool, NULL_HANDLE, BlendTargetArrayHandle, RasterizerStateHandle, RasterizerStatePool, RasterizerStateView, + DepthStencilStateHandle, DepthStencilStatePool, DepthStencilStateView, BlendTargetHandle, BlendTargetPool, BlendTargetView, + BlendStateHandle, BlendStatePool, BlendStateView } from '../renderer/core/memory-pools'; export class RasterizerState { private h: RasterizerStateHandle; @@ -58,9 +60,9 @@ export class RasterizerState { else return false; } set isFrontFaceCCW (val: boolean) { RasterizerStatePool.set(this.h, RasterizerStateView.IS_FRONT_FACE_CCW, val ? 1 : 0); } - get depthBiasEnabled (): boolean { + get depthBiasEnabled (): boolean { if (RasterizerStatePool.get(this.h, RasterizerStateView.DEPTH_BIAS_ENABLED)) return true; - else return false; + else return false; } set depthBiasEnabled (val: boolean) { RasterizerStatePool.set(this.h, RasterizerStateView.DEPTH_BIAS_ENABLED, val ? 1 : 0); } get depthBias (): number { return RasterizerStatePool.get(this.h, RasterizerStateView.DEPTH_BIAS); } @@ -84,7 +86,7 @@ export class RasterizerState { get handle (): RasterizerStateHandle { return this.h; } public reset () { - this.assignProperties(false, PolygonMode.FILL, ShadeModel.GOURAND, CullMode.BACK, true, 0, + this.assignProperties(false, PolygonMode.FILL, ShadeModel.GOURAND, CullMode.BACK, true, false, 0, 0.0, 0.0, true, false, 1.0); } @@ -169,7 +171,7 @@ export class DepthStencilState { if (DepthStencilStatePool.get(this.h, DepthStencilStateView.DEPTH_TEST)) return true; else return false; } - set depthTest(val: boolean) { DepthStencilStatePool.set(this.h, DepthStencilStateView.DEPTH_TEST, val ? 1 : 0); } + set depthTest (val: boolean) { DepthStencilStatePool.set(this.h, DepthStencilStateView.DEPTH_TEST, val ? 1 : 0); } get depthWrite (): boolean { if (DepthStencilStatePool.get(this.h, DepthStencilStateView.DEPTH_WRITE)) return true; else return false; @@ -189,7 +191,7 @@ export class DepthStencilState { get stencilWriteMaskFront (): number { return DepthStencilStatePool.get(this.h, DepthStencilStateView.STENCIL_WRITE_MASK_FRONT); } set stencilWriteMaskFront (val: number) { DepthStencilStatePool.set(this.h, DepthStencilStateView.STENCIL_WRITE_MASK_FRONT, val); } get stencilFailOpFront (): StencilOp { return DepthStencilStatePool.get(this.h, DepthStencilStateView.STENCIL_FAIL_OP_FRONT); } - set stencilFailOpFront (val: StencilOp) { DepthStencilStatePool.set(this.h, DepthStencilStateView.STENCIL_FAIL_OP_FRONT, val); } + set stencilFailOpFront (val: StencilOp) { DepthStencilStatePool.set(this.h, DepthStencilStateView.STENCIL_FAIL_OP_FRONT, val); } get stencilZFailOpFront (): StencilOp { return DepthStencilStatePool.get(this.h, DepthStencilStateView.STENCIL_Z_FAIL_OP_FRONT); } set stencilZFailOpFront (val: StencilOp) { DepthStencilStatePool.set(this.h, DepthStencilStateView.STENCIL_Z_FAIL_OP_FRONT, val); } get stencilPassOpFront (): StencilOp { return DepthStencilStatePool.get(this.h, DepthStencilStateView.STENCIL_PASS_OP_FRONT); } @@ -423,7 +425,7 @@ export class BlendState { this.isIndepend = false; BlendStatePool.setVec4(this.h, BlendStateView.BLEND_COLOR, new Color(0, 0, 0, 0)); - let targets = this.targets; + const targets = this.targets; for (let i = 1, len = targets.length; i < len; ++i) { targets[i].destroy(); } @@ -436,7 +438,7 @@ export class BlendState { public destroy () { BlendStatePool.free(this.h); this.h = NULL_HANDLE; - + BlendTargetArrayPool.free(this.hBt); this.hBt = NULL_HANDLE; diff --git a/cocos/core/gfx/pipeline-state.ts b/cocos/core/gfx/pipeline-state.ts index 89d7a67e9a..6013281fef 100644 --- a/cocos/core/gfx/pipeline-state.ts +++ b/cocos/core/gfx/pipeline-state.ts @@ -3,12 +3,19 @@ * @module gfx */ +import { Attribute } from './input-assembler'; +import { Color } from './define-class'; +import { Device } from './device'; +import { PipelineLayout } from './pipeline-layout'; +import { RenderPass } from './render-pass'; +import { Shader } from './shader'; import { BlendFactor, BlendOp, ColorMask, ComparisonFunc, CullMode, + DynamicStateFlagBit, DynamicStateFlags, Obj, ObjectType, @@ -16,14 +23,7 @@ import { PrimitiveMode, ShadeModel, StencilOp, - DynamicStateFlagBit, } from './define'; -import { Color } from './define-class'; -import { Device } from './device'; -import { Attribute } from './input-assembler'; -import { RenderPass } from './render-pass'; -import { Shader } from './shader'; -import { PipelineLayout } from './pipeline-layout'; import { NULL_HANDLE, RawBufferHandle } from '../renderer/core/memory-pools'; /** @@ -31,7 +31,7 @@ import { NULL_HANDLE, RawBufferHandle } from '../renderer/core/memory-pools'; * @zh GFX 光栅化状态。 */ export class RasterizerState { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public isDiscard: boolean = false, @@ -68,6 +68,7 @@ export class RasterizerState { } get handle (): RawBufferHandle { return NULL_HANDLE; } + public destroy () {} } @@ -76,7 +77,7 @@ export class RasterizerState { * @zh GFX 深度模板状态。 */ export class DepthStencilState { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public depthTest: boolean = true, @@ -127,6 +128,7 @@ export class DepthStencilState { } get handle (): RawBufferHandle { return NULL_HANDLE; } + public destroy () {} } @@ -135,7 +137,7 @@ export class DepthStencilState { * @zh GFX 混合目标。 */ export class BlendTarget { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public blend: boolean = false, @@ -164,6 +166,7 @@ export class BlendTarget { } get handle (): RawBufferHandle { return NULL_HANDLE; } + public destroy () {} } @@ -172,7 +175,7 @@ export class BlendTarget { * @zh GFX 混合状态。 */ export class BlendState { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public isA2C: boolean = false, @@ -209,6 +212,7 @@ export class BlendState { } get handle (): RawBufferHandle { return NULL_HANDLE; } + public destroy () {} } @@ -217,7 +221,7 @@ export class BlendState { * @zh GFX 输入状态。 */ export class InputState { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public attributes: Attribute[] = [], @@ -225,7 +229,7 @@ export class InputState { } export class PipelineStateInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public shader: Shader, @@ -245,7 +249,6 @@ export class PipelineStateInfo { * @zh GFX 管线状态。 */ export abstract class PipelineState extends Obj { - /** * @en Get current shader. * @zh GFX 着色器。 @@ -275,7 +278,7 @@ export abstract class PipelineState extends Obj { * @zh GFX 光栅化状态。 */ get rasterizerState (): RasterizerState { - return this._rs as RasterizerState; + return this._rs as RasterizerState; } /** @@ -283,7 +286,7 @@ export abstract class PipelineState extends Obj { * @zh GFX 深度模板状态。 */ get depthStencilState (): DepthStencilState { - return this._dss as DepthStencilState; + return this._dss as DepthStencilState; } /** @@ -291,7 +294,7 @@ export abstract class PipelineState extends Obj { * @zh GFX 混合状态。 */ get blendState (): BlendState { - return this._bs as BlendState; + return this._bs as BlendState; } /** diff --git a/cocos/core/gfx/polyfill-legacy-cc.ts b/cocos/core/gfx/polyfill-legacy-cc.ts index 0f65a3287c..d334b1d9dd 100644 --- a/cocos/core/gfx/polyfill-legacy-cc.ts +++ b/cocos/core/gfx/polyfill-legacy-cc.ts @@ -13,20 +13,20 @@ import { RenderPass } from './render-pass'; import { Sampler } from './sampler'; import { Shader } from './shader'; import { Texture } from './texture'; -import { FormatSize,FormatSurfaceSize,GetTypeSize,getTypedArrayConstructor,MAX_ATTACHMENTS, - ObjectType,Obj,AttributeName,Type,Format,BufferUsageBit,MemoryUsageBit,BufferFlagBit, - BufferAccessBit,PrimitiveMode,PolygonMode,ShadeModel,CullMode,ComparisonFunc,StencilOp,BlendOp, - BlendFactor,ColorMask,Filter,Address,TextureType,TextureUsageBit,SampleCount,TextureFlagBit,ShaderStageFlagBit, - DescriptorType,CommandBufferType,LoadOp,StoreOp,TextureLayout,PipelineBindPoint,DynamicStateFlagBit,StencilFace, - QueueType,ClearFlag,FormatType, - FormatInfo,MemoryStatus,FormatInfos } from './define'; -import { Rect, Viewport, Color, Offset, Extent, TextureSubres, TextureCopy, BufferTextureCopy } from './define-class'; +import { Address, AttributeName, BlendFactor, BlendOp, BufferAccessBit, + BufferFlagBit, BufferUsageBit, ClearFlag, ColorMask, CommandBufferType, ComparisonFunc, CullMode, DescriptorType, + DynamicStateFlagBit, Filter, Format, FormatInfo, FormatInfos, FormatSize, FormatSurfaceSize, FormatType, + GetTypeSize, LoadOp, MAX_ATTACHMENTS, MemoryStatus, MemoryUsageBit, Obj, ObjectType, PipelineBindPoint, PolygonMode, + PrimitiveMode, QueueType, SampleCount, ShadeModel, ShaderStageFlagBit, StencilFace, StencilOp, StoreOp, + TextureFlagBit, TextureLayout, TextureType, + TextureUsageBit, Type, getTypedArrayConstructor } from './define'; +import { BufferTextureCopy, Color, Extent, Offset, Rect, TextureCopy, TextureSubres, Viewport } from './define-class'; -export const polyfillCC = {Device,Buffer,Texture,Sampler,Shader,InputAssembler,RenderPass,Framebuffer,PipelineState,CommandBuffer,Queue, - FormatSize,FormatSurfaceSize,GetTypeSize,getTypedArrayConstructor,MAX_ATTACHMENTS, - ObjectType,Obj,AttributeName,Type,Format,BufferUsageBit,MemoryUsageBit,BufferFlagBit, - BufferAccessBit,PrimitiveMode,PolygonMode,ShadeModel,CullMode,ComparisonFunc,StencilOp,BlendOp, - BlendFactor,ColorMask,Filter,Address,TextureType,TextureUsageBit,SampleCount,TextureFlagBit,ShaderStageFlagBit, - DescriptorType,CommandBufferType,LoadOp,StoreOp,TextureLayout,PipelineBindPoint,DynamicStateFlagBit,StencilFace, - QueueType,Rect,Viewport,Color,ClearFlag,Offset,Extent,TextureSubres,TextureCopy,BufferTextureCopy,FormatType, - FormatInfo,MemoryStatus,FormatInfos}; \ No newline at end of file +export const polyfillCC = { Device, Buffer, Texture, Sampler, Shader, InputAssembler, RenderPass, Framebuffer, PipelineState, CommandBuffer, Queue, + FormatSize, FormatSurfaceSize, GetTypeSize, getTypedArrayConstructor, MAX_ATTACHMENTS, + ObjectType, Obj, AttributeName, Type, Format, BufferUsageBit, MemoryUsageBit, BufferFlagBit, + BufferAccessBit, PrimitiveMode, PolygonMode, ShadeModel, CullMode, ComparisonFunc, StencilOp, BlendOp, + BlendFactor, ColorMask, Filter, Address, TextureType, TextureUsageBit, SampleCount, TextureFlagBit, ShaderStageFlagBit, + DescriptorType, CommandBufferType, LoadOp, StoreOp, TextureLayout, PipelineBindPoint, DynamicStateFlagBit, StencilFace, + QueueType, Rect, Viewport, Color, ClearFlag, Offset, Extent, TextureSubres, TextureCopy, BufferTextureCopy, FormatType, + FormatInfo, MemoryStatus, FormatInfos }; diff --git a/cocos/core/gfx/queue.ts b/cocos/core/gfx/queue.ts index 15496e62be..08004fa026 100644 --- a/cocos/core/gfx/queue.ts +++ b/cocos/core/gfx/queue.ts @@ -4,12 +4,12 @@ */ import { CommandBuffer } from './command-buffer'; -import { Obj, ObjectType, QueueType } from './define'; import { Device } from './device'; import { Fence } from './fence'; +import { Obj, ObjectType, QueueType } from './define'; export class QueueInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public type: QueueType = QueueType.GRAPHICS, @@ -41,12 +41,12 @@ export abstract class Queue extends Obj { this._device = device; } + public isAsync () { return this._isAsync; } + public abstract initialize (info: QueueInfo): boolean; public abstract destroy (): void; - public isAsync () { return this._isAsync; } - /** * @en Submit command buffers. * @zh 提交命令缓冲数组。 diff --git a/cocos/core/gfx/render-pass.ts b/cocos/core/gfx/render-pass.ts index b1cab2d8d2..8c88631dc7 100644 --- a/cocos/core/gfx/render-pass.ts +++ b/cocos/core/gfx/render-pass.ts @@ -3,6 +3,8 @@ * @module gfx */ +import { Device } from './device'; +import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; import { Format, LoadOp, @@ -12,15 +14,13 @@ import { StoreOp, TextureLayout, } from './define'; -import { Device } from './device'; -import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; /** * @en Color attachment. * @zh GFX 颜色附件。 */ export class ColorAttachment { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public format: Format = Format.UNKNOWN, @@ -37,7 +37,7 @@ export class ColorAttachment { * @zh GFX 深度模板附件。 */ export class DepthStencilAttachment { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public format: Format = Format.UNKNOWN, @@ -52,7 +52,7 @@ export class DepthStencilAttachment { } export class SubPassInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public bindPoint: PipelineBindPoint = PipelineBindPoint.GRAPHICS, @@ -65,7 +65,7 @@ export class SubPassInfo { } export class RenderPassInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public colorAttachments: ColorAttachment[] = [], @@ -86,9 +86,9 @@ export abstract class RenderPass extends Obj { protected _depthStencilInfo: DepthStencilAttachment | null = null; - protected _subPasses : SubPassInfo[] = []; + protected _subPasses: SubPassInfo[] = []; - protected _hash: number = 0; + protected _hash = 0; get colorAttachments () { return this._colorInfos; } get depthStencilAttachment () { return this._depthStencilInfo; } @@ -100,10 +100,6 @@ export abstract class RenderPass extends Obj { this._device = device; } - public abstract initialize (info: RenderPassInfo): boolean; - - public abstract destroy (): void; - // Based on render pass compatibility protected computeHash (): number { let res = ''; @@ -143,4 +139,8 @@ export abstract class RenderPass extends Obj { return murmurhash2_32_gc(res, 666); } + + public abstract initialize (info: RenderPassInfo): boolean; + + public abstract destroy (): void; } diff --git a/cocos/core/gfx/sampler.ts b/cocos/core/gfx/sampler.ts index bc1b57816a..1fe47dda28 100644 --- a/cocos/core/gfx/sampler.ts +++ b/cocos/core/gfx/sampler.ts @@ -3,12 +3,12 @@ * @module gfx */ -import { Address, ComparisonFunc, Filter, Obj, ObjectType } from './define'; import { Color } from './define-class'; import { Device } from './device'; +import { Address, ComparisonFunc, Filter, Obj, ObjectType } from './define'; export class SamplerInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public minFilter: Filter = Filter.LINEAR, @@ -53,12 +53,12 @@ export abstract class Sampler extends Obj { protected _addressU: Address = Address.WRAP; protected _addressV: Address = Address.WRAP; protected _addressW: Address = Address.WRAP; - protected _maxAnisotropy: number = 16; + protected _maxAnisotropy = 16; protected _cmpFunc: ComparisonFunc = ComparisonFunc.NEVER; protected _borderColor: Color = new Color(); - protected _minLOD: number = 0; - protected _maxLOD: number = 0; - protected _mipLODBias: number = 0.0; + protected _minLOD = 0; + protected _maxLOD = 0; + protected _mipLODBias = 0.0; constructor (device: Device) { super(ObjectType.SAMPLER); diff --git a/cocos/core/gfx/shader.ts b/cocos/core/gfx/shader.ts index cc09d1e5d8..bbd74d720f 100644 --- a/cocos/core/gfx/shader.ts +++ b/cocos/core/gfx/shader.ts @@ -3,9 +3,9 @@ * @module gfx */ -import { Obj, ObjectType, ShaderStageFlagBit, Type } from './define'; -import { Device } from './device'; import { Attribute } from './input-assembler'; +import { Device } from './device'; +import { Obj, ObjectType, ShaderStageFlagBit, Type } from './define'; export interface IShaderStage { stage: ShaderStageFlagBit; @@ -13,7 +13,7 @@ export interface IShaderStage { } export class ShaderStage implements IShaderStage { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public stage: ShaderStageFlagBit = ShaderStageFlagBit.NONE, @@ -32,7 +32,7 @@ export interface IUniform { * @zh GFX uniform。 */ export class Uniform implements IUniform { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public name: string = '', @@ -46,7 +46,7 @@ export class Uniform implements IUniform { * @zh GFX uniform 块。 */ export class UniformBlock { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public set: number = -1, @@ -62,7 +62,7 @@ export class UniformBlock { * @zh GFX Uniform 采样器。 */ export class UniformSampler { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public set: number = -1, @@ -74,7 +74,7 @@ export class UniformSampler { } export class ShaderInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public name: string = '', @@ -90,7 +90,7 @@ export class ShaderInfo { * @zh GFX 着色器。 */ export abstract class Shader extends Obj { - private static _shaderIdGen: number = 0; + private static _shaderIdGen = 0; /** * @en Get current shader id. @@ -124,7 +124,7 @@ export abstract class Shader extends Obj { protected _id: number; - protected _name: string = ''; + protected _name = ''; protected _stages: ShaderStage[] = []; diff --git a/cocos/core/gfx/texture.ts b/cocos/core/gfx/texture.ts index fd8020e1b3..f27912891e 100644 --- a/cocos/core/gfx/texture.ts +++ b/cocos/core/gfx/texture.ts @@ -3,6 +3,7 @@ * @module gfx */ +import { Device } from './device'; import { Format, Obj, @@ -14,10 +15,9 @@ import { TextureUsage, TextureUsageBit, } from './define'; -import { Device } from './device'; export class TextureInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public type: TextureType, @@ -34,7 +34,7 @@ export class TextureInfo { } export class TextureViewInfo { - declare private token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( public texture: Texture, @@ -47,7 +47,7 @@ export class TextureViewInfo { ) {} } -export function IsPowerOf2 (x: number): boolean{ +export function IsPowerOf2 (x: number): boolean { return x > 0 && (x & (x - 1)) === 0; } @@ -158,15 +158,15 @@ export abstract class Texture extends Obj { protected _type: TextureType = TextureType.TEX2D; protected _usage: TextureUsage = TextureUsageBit.NONE; protected _format: Format = Format.UNKNOWN; - protected _width: number = 0; - protected _height: number = 0; - protected _depth: number = 1; - protected _layerCount: number = 1; - protected _levelCount: number = 1; + protected _width = 0; + protected _height = 0; + protected _depth = 1; + protected _layerCount = 1; + protected _levelCount = 1; protected _samples: SampleCount = SampleCount.X1; protected _flags: TextureFlags = TextureFlagBit.NONE; - protected _isPowerOf2: boolean = false; - protected _size: number = 0; + protected _isPowerOf2 = false; + protected _size = 0; protected _buffer: ArrayBuffer | null = null; constructor (device: Device) { diff --git a/cocos/core/gfx/webgl/webgl-command-buffer.ts b/cocos/core/gfx/webgl/webgl-command-buffer.ts index 5b117e2b8a..da3453ae02 100644 --- a/cocos/core/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/core/gfx/webgl/webgl-command-buffer.ts @@ -48,7 +48,7 @@ export class WebGLCommandBuffer extends CommandBuffer { public cmdPackage: WebGLCmdPackage = new WebGLCmdPackage(); protected _webGLAllocator: WebGLCommandAllocator | null = null; - protected _isInRenderPass: boolean = false; + protected _isInRenderPass = false; protected _curGPUPipelineState: IWebGLGPUPipelineState | null = null; protected _curGPUInputAssembler: IWebGLGPUInputAssembler | null = null; protected _curGPUDescriptorSets: IWebGLGPUDescriptorSet[] = []; @@ -61,7 +61,7 @@ export class WebGLCommandBuffer extends CommandBuffer { protected _curDepthBounds: IWebGLDepthBounds | null = null; protected _curStencilWriteMask: IWebGLStencilWriteMask | null = null; protected _curStencilCompareMask: IWebGLStencilCompareMask | null = null; - protected _isStateInvalied: boolean = false; + protected _isStateInvalied = false; public initialize (info: CommandBufferInfo): boolean { @@ -409,7 +409,7 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - // tslint:disable: max-line-length + public execute (cmdBuffs: CommandBuffer[], count: number) { for (let i = 0; i < count; ++i) { diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index d5ddadca16..5588eb7574 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -2,436 +2,442 @@ import { CachedArray } from '../../memop/cached-array'; import { error, errorID } from '../../platform/debug'; import { BufferSource, DrawInfo, IndirectBuffer } from '../buffer'; import { WebGLCommandAllocator } from './webgl-command-allocator'; -import { IWebGLDepthBias, IWebGLDepthBounds, IWebGLStencilCompareMask, IWebGLStencilWriteMask } from './webgl-command-buffer'; +import { + IWebGLDepthBias, IWebGLDepthBounds, IWebGLStencilCompareMask, IWebGLStencilWriteMask, +} from './webgl-command-buffer'; import { WebGLEXT } from './webgl-define'; import { WebGLDevice } from './webgl-device'; -import { IWebGLGPUInputAssembler, IWebGLGPUUniform, IWebGLAttrib, IWebGLGPUDescriptorSet, IWebGLGPUBuffer, IWebGLGPUFramebuffer, IWebGLGPUInput, - IWebGLGPUPipelineState, IWebGLGPUShader, IWebGLGPUTexture, IWebGLGPUUniformBlock, IWebGLGPUUniformSampler, IWebGLGPURenderPass } from './webgl-gpu-objects'; -import { BufferUsageBit, ClearFlag, ColorMask, CullMode, Format, +import { + IWebGLGPUInputAssembler, IWebGLGPUUniform, IWebGLAttrib, IWebGLGPUDescriptorSet, IWebGLGPUBuffer, IWebGLGPUFramebuffer, IWebGLGPUInput, + IWebGLGPUPipelineState, IWebGLGPUShader, IWebGLGPUTexture, IWebGLGPUUniformBlock, IWebGLGPUUniformSampler, IWebGLGPURenderPass, +} from './webgl-gpu-objects'; +import { + BufferUsageBit, ClearFlag, ColorMask, CullMode, Format, FormatInfos, FormatSize, LoadOp, MemoryUsageBit, SampleCount, ShaderStageFlagBit, StencilFace, - TextureFlagBit, TextureType, Type, FormatInfo, DynamicStateFlagBit } from '../define'; -import { BufferTextureCopy, Color, Rect, Viewport } from '../define-class'; + TextureFlagBit, TextureType, Type, FormatInfo, DynamicStateFlagBit, +} from '../define'; +import { + BufferTextureCopy, Color, Rect, Viewport, +} from '../define-class'; export function GFXFormatToWebGLType (format: Format, gl: WebGLRenderingContext): GLenum { switch (format) { - case Format.R8: return gl.UNSIGNED_BYTE; - case Format.R8SN: return gl.BYTE; - case Format.R8UI: return gl.UNSIGNED_BYTE; - case Format.R8I: return gl.BYTE; - case Format.R16F: return WebGLEXT.HALF_FLOAT_OES; - case Format.R16UI: return gl.UNSIGNED_SHORT; - case Format.R16I: return gl.SHORT; - case Format.R32F: return gl.FLOAT; - case Format.R32UI: return gl.UNSIGNED_INT; - case Format.R32I: return gl.INT; + case Format.R8: return gl.UNSIGNED_BYTE; + case Format.R8SN: return gl.BYTE; + case Format.R8UI: return gl.UNSIGNED_BYTE; + case Format.R8I: return gl.BYTE; + case Format.R16F: return WebGLEXT.HALF_FLOAT_OES; + case Format.R16UI: return gl.UNSIGNED_SHORT; + case Format.R16I: return gl.SHORT; + case Format.R32F: return gl.FLOAT; + case Format.R32UI: return gl.UNSIGNED_INT; + case Format.R32I: return gl.INT; - case Format.RG8: return gl.UNSIGNED_BYTE; - case Format.RG8SN: return gl.BYTE; - case Format.RG8UI: return gl.UNSIGNED_BYTE; - case Format.RG8I: return gl.BYTE; - case Format.RG16F: return WebGLEXT.HALF_FLOAT_OES; - case Format.RG16UI: return gl.UNSIGNED_SHORT; - case Format.RG16I: return gl.SHORT; - case Format.RG32F: return gl.FLOAT; - case Format.RG32UI: return gl.UNSIGNED_INT; - case Format.RG32I: return gl.INT; + case Format.RG8: return gl.UNSIGNED_BYTE; + case Format.RG8SN: return gl.BYTE; + case Format.RG8UI: return gl.UNSIGNED_BYTE; + case Format.RG8I: return gl.BYTE; + case Format.RG16F: return WebGLEXT.HALF_FLOAT_OES; + case Format.RG16UI: return gl.UNSIGNED_SHORT; + case Format.RG16I: return gl.SHORT; + case Format.RG32F: return gl.FLOAT; + case Format.RG32UI: return gl.UNSIGNED_INT; + case Format.RG32I: return gl.INT; - case Format.RGB8: return gl.UNSIGNED_BYTE; - case Format.SRGB8: return gl.UNSIGNED_BYTE; - case Format.RGB8SN: return gl.BYTE; - case Format.RGB8UI: return gl.UNSIGNED_BYTE; - case Format.RGB8I: return gl.BYTE; - case Format.RGB16F: return WebGLEXT.HALF_FLOAT_OES; - case Format.RGB16UI: return gl.UNSIGNED_SHORT; - case Format.RGB16I: return gl.SHORT; - case Format.RGB32F: return gl.FLOAT; - case Format.RGB32UI: return gl.UNSIGNED_INT; - case Format.RGB32I: return gl.INT; + case Format.RGB8: return gl.UNSIGNED_BYTE; + case Format.SRGB8: return gl.UNSIGNED_BYTE; + case Format.RGB8SN: return gl.BYTE; + case Format.RGB8UI: return gl.UNSIGNED_BYTE; + case Format.RGB8I: return gl.BYTE; + case Format.RGB16F: return WebGLEXT.HALF_FLOAT_OES; + case Format.RGB16UI: return gl.UNSIGNED_SHORT; + case Format.RGB16I: return gl.SHORT; + case Format.RGB32F: return gl.FLOAT; + case Format.RGB32UI: return gl.UNSIGNED_INT; + case Format.RGB32I: return gl.INT; - case Format.BGRA8: return gl.UNSIGNED_BYTE; - case Format.RGBA8: return gl.UNSIGNED_BYTE; - case Format.SRGB8_A8: return gl.UNSIGNED_BYTE; - case Format.RGBA8SN: return gl.BYTE; - case Format.RGBA8UI: return gl.UNSIGNED_BYTE; - case Format.RGBA8I: return gl.BYTE; - case Format.RGBA16F: return WebGLEXT.HALF_FLOAT_OES; - case Format.RGBA16UI: return gl.UNSIGNED_SHORT; - case Format.RGBA16I: return gl.SHORT; - case Format.RGBA32F: return gl.FLOAT; - case Format.RGBA32UI: return gl.UNSIGNED_INT; - case Format.RGBA32I: return gl.INT; + case Format.BGRA8: return gl.UNSIGNED_BYTE; + case Format.RGBA8: return gl.UNSIGNED_BYTE; + case Format.SRGB8_A8: return gl.UNSIGNED_BYTE; + case Format.RGBA8SN: return gl.BYTE; + case Format.RGBA8UI: return gl.UNSIGNED_BYTE; + case Format.RGBA8I: return gl.BYTE; + case Format.RGBA16F: return WebGLEXT.HALF_FLOAT_OES; + case Format.RGBA16UI: return gl.UNSIGNED_SHORT; + case Format.RGBA16I: return gl.SHORT; + case Format.RGBA32F: return gl.FLOAT; + case Format.RGBA32UI: return gl.UNSIGNED_INT; + case Format.RGBA32I: return gl.INT; - case Format.R5G6B5: return gl.UNSIGNED_SHORT_5_6_5; - case Format.R11G11B10F: return gl.FLOAT; - case Format.RGB5A1: return gl.UNSIGNED_SHORT_5_5_5_1; - case Format.RGBA4: return gl.UNSIGNED_SHORT_4_4_4_4; - case Format.RGB10A2: return gl.UNSIGNED_BYTE; - case Format.RGB10A2UI: return gl.UNSIGNED_INT; - case Format.RGB9E5: return gl.UNSIGNED_BYTE; + case Format.R5G6B5: return gl.UNSIGNED_SHORT_5_6_5; + case Format.R11G11B10F: return gl.FLOAT; + case Format.RGB5A1: return gl.UNSIGNED_SHORT_5_5_5_1; + case Format.RGBA4: return gl.UNSIGNED_SHORT_4_4_4_4; + case Format.RGB10A2: return gl.UNSIGNED_BYTE; + case Format.RGB10A2UI: return gl.UNSIGNED_INT; + case Format.RGB9E5: return gl.UNSIGNED_BYTE; - case Format.D16: return gl.UNSIGNED_SHORT; - case Format.D16S8: return WebGLEXT.UNSIGNED_INT_24_8_WEBGL; // not supported, fallback - case Format.D24: return gl.UNSIGNED_INT; - case Format.D24S8: return WebGLEXT.UNSIGNED_INT_24_8_WEBGL; - case Format.D32F: return gl.UNSIGNED_INT; // not supported, fallback - case Format.D32F_S8: return WebGLEXT.UNSIGNED_INT_24_8_WEBGL; // not supported, fallback + case Format.D16: return gl.UNSIGNED_SHORT; + case Format.D16S8: return WebGLEXT.UNSIGNED_INT_24_8_WEBGL; // not supported, fallback + case Format.D24: return gl.UNSIGNED_INT; + case Format.D24S8: return WebGLEXT.UNSIGNED_INT_24_8_WEBGL; + case Format.D32F: return gl.UNSIGNED_INT; // not supported, fallback + case Format.D32F_S8: return WebGLEXT.UNSIGNED_INT_24_8_WEBGL; // not supported, fallback - case Format.BC1: return gl.UNSIGNED_BYTE; - case Format.BC1_SRGB: return gl.UNSIGNED_BYTE; - case Format.BC2: return gl.UNSIGNED_BYTE; - case Format.BC2_SRGB: return gl.UNSIGNED_BYTE; - case Format.BC3: return gl.UNSIGNED_BYTE; - case Format.BC3_SRGB: return gl.UNSIGNED_BYTE; - case Format.BC4: return gl.UNSIGNED_BYTE; - case Format.BC4_SNORM: return gl.BYTE; - case Format.BC5: return gl.UNSIGNED_BYTE; - case Format.BC5_SNORM: return gl.BYTE; - case Format.BC6H_SF16: return gl.FLOAT; - case Format.BC6H_UF16: return gl.FLOAT; - case Format.BC7: return gl.UNSIGNED_BYTE; - case Format.BC7_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC1: return gl.UNSIGNED_BYTE; + case Format.BC1_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC2: return gl.UNSIGNED_BYTE; + case Format.BC2_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC3: return gl.UNSIGNED_BYTE; + case Format.BC3_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC4: return gl.UNSIGNED_BYTE; + case Format.BC4_SNORM: return gl.BYTE; + case Format.BC5: return gl.UNSIGNED_BYTE; + case Format.BC5_SNORM: return gl.BYTE; + case Format.BC6H_SF16: return gl.FLOAT; + case Format.BC6H_UF16: return gl.FLOAT; + case Format.BC7: return gl.UNSIGNED_BYTE; + case Format.BC7_SRGB: return gl.UNSIGNED_BYTE; - case Format.ETC_RGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_RGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_SRGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_RGB8_A1: return gl.UNSIGNED_BYTE; - case Format.ETC2_SRGB8_A1: return gl.UNSIGNED_BYTE; - case Format.ETC2_RGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_SRGB8: return gl.UNSIGNED_BYTE; - case Format.EAC_R11: return gl.UNSIGNED_BYTE; - case Format.EAC_R11SN: return gl.BYTE; - case Format.EAC_RG11: return gl.UNSIGNED_BYTE; - case Format.EAC_RG11SN: return gl.BYTE; + case Format.ETC_RGB8: return gl.UNSIGNED_BYTE; + case Format.ETC2_RGB8: return gl.UNSIGNED_BYTE; + case Format.ETC2_SRGB8: return gl.UNSIGNED_BYTE; + case Format.ETC2_RGB8_A1: return gl.UNSIGNED_BYTE; + case Format.ETC2_SRGB8_A1: return gl.UNSIGNED_BYTE; + case Format.EAC_R11: return gl.UNSIGNED_BYTE; + case Format.EAC_R11SN: return gl.BYTE; + case Format.EAC_RG11: return gl.UNSIGNED_BYTE; + case Format.EAC_RG11SN: return gl.BYTE; - case Format.PVRTC_RGB2: return gl.UNSIGNED_BYTE; - case Format.PVRTC_RGBA2: return gl.UNSIGNED_BYTE; - case Format.PVRTC_RGB4: return gl.UNSIGNED_BYTE; - case Format.PVRTC_RGBA4: return gl.UNSIGNED_BYTE; - case Format.PVRTC2_2BPP: return gl.UNSIGNED_BYTE; - case Format.PVRTC2_4BPP: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGB2: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGBA2: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGB4: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGBA4: return gl.UNSIGNED_BYTE; + case Format.PVRTC2_2BPP: return gl.UNSIGNED_BYTE; + case Format.PVRTC2_4BPP: return gl.UNSIGNED_BYTE; - case Format.ASTC_RGBA_4x4: - case Format.ASTC_RGBA_5x4: - case Format.ASTC_RGBA_5x5: - case Format.ASTC_RGBA_6x5: - case Format.ASTC_RGBA_6x6: - case Format.ASTC_RGBA_8x5: - case Format.ASTC_RGBA_8x6: - case Format.ASTC_RGBA_8x8: - case Format.ASTC_RGBA_10x5: - case Format.ASTC_RGBA_10x6: - case Format.ASTC_RGBA_10x8: - case Format.ASTC_RGBA_10x10: - case Format.ASTC_RGBA_12x10: - case Format.ASTC_RGBA_12x12: - case Format.ASTC_SRGBA_4x4: - case Format.ASTC_SRGBA_5x4: - case Format.ASTC_SRGBA_5x5: - case Format.ASTC_SRGBA_6x5: - case Format.ASTC_SRGBA_6x6: - case Format.ASTC_SRGBA_8x5: - case Format.ASTC_SRGBA_8x6: - case Format.ASTC_SRGBA_8x8: - case Format.ASTC_SRGBA_10x5: - case Format.ASTC_SRGBA_10x6: - case Format.ASTC_SRGBA_10x8: - case Format.ASTC_SRGBA_10x10: - case Format.ASTC_SRGBA_12x10: - case Format.ASTC_SRGBA_12x12: - return gl.UNSIGNED_BYTE; + case Format.ASTC_RGBA_4x4: + case Format.ASTC_RGBA_5x4: + case Format.ASTC_RGBA_5x5: + case Format.ASTC_RGBA_6x5: + case Format.ASTC_RGBA_6x6: + case Format.ASTC_RGBA_8x5: + case Format.ASTC_RGBA_8x6: + case Format.ASTC_RGBA_8x8: + case Format.ASTC_RGBA_10x5: + case Format.ASTC_RGBA_10x6: + case Format.ASTC_RGBA_10x8: + case Format.ASTC_RGBA_10x10: + case Format.ASTC_RGBA_12x10: + case Format.ASTC_RGBA_12x12: + case Format.ASTC_SRGBA_4x4: + case Format.ASTC_SRGBA_5x4: + case Format.ASTC_SRGBA_5x5: + case Format.ASTC_SRGBA_6x5: + case Format.ASTC_SRGBA_6x6: + case Format.ASTC_SRGBA_8x5: + case Format.ASTC_SRGBA_8x6: + case Format.ASTC_SRGBA_8x8: + case Format.ASTC_SRGBA_10x5: + case Format.ASTC_SRGBA_10x6: + case Format.ASTC_SRGBA_10x8: + case Format.ASTC_SRGBA_10x10: + case Format.ASTC_SRGBA_12x10: + case Format.ASTC_SRGBA_12x12: + return gl.UNSIGNED_BYTE; - default: { - return gl.UNSIGNED_BYTE; - } + default: { + return gl.UNSIGNED_BYTE; + } } } export function GFXFormatToWebGLInternalFormat (format: Format, gl: WebGLRenderingContext): GLenum { switch (format) { - case Format.A8: return gl.ALPHA; - case Format.L8: return gl.LUMINANCE; - case Format.LA8: return gl.LUMINANCE_ALPHA; - case Format.RGB8: return gl.RGB; - case Format.RGB16F: return gl.RGB; - case Format.RGB32F: return gl.RGB; - case Format.BGRA8: return gl.RGBA; - case Format.RGBA8: return gl.RGBA; - case Format.RGBA16F: return gl.RGBA; - case Format.RGBA32F: return gl.RGBA; - case Format.R5G6B5: return gl.RGB565; - case Format.RGB5A1: return gl.RGB5_A1; - case Format.RGBA4: return gl.RGBA4; - case Format.D16: return gl.DEPTH_COMPONENT; - case Format.D16S8: return gl.DEPTH_STENCIL; - case Format.D24: return gl.DEPTH_COMPONENT; - case Format.D24S8: return gl.DEPTH_STENCIL; - case Format.D32F: return gl.DEPTH_COMPONENT; - case Format.D32F_S8: return gl.DEPTH_STENCIL; + case Format.A8: return gl.ALPHA; + case Format.L8: return gl.LUMINANCE; + case Format.LA8: return gl.LUMINANCE_ALPHA; + case Format.RGB8: return gl.RGB; + case Format.RGB16F: return gl.RGB; + case Format.RGB32F: return gl.RGB; + case Format.BGRA8: return gl.RGBA; + case Format.RGBA8: return gl.RGBA; + case Format.RGBA16F: return gl.RGBA; + case Format.RGBA32F: return gl.RGBA; + case Format.R5G6B5: return gl.RGB565; + case Format.RGB5A1: return gl.RGB5_A1; + case Format.RGBA4: return gl.RGBA4; + case Format.D16: return gl.DEPTH_COMPONENT; + case Format.D16S8: return gl.DEPTH_STENCIL; + case Format.D24: return gl.DEPTH_COMPONENT; + case Format.D24S8: return gl.DEPTH_STENCIL; + case Format.D32F: return gl.DEPTH_COMPONENT; + case Format.D32F_S8: return gl.DEPTH_STENCIL; - case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; - case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; - case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; - case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; - case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; - case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; - case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; - case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; - case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; - case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; - case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; - case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; - case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; - case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; + case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; + case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; + case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; + case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; + case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; + case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; + case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; - case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; - case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; - case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; - case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; - case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; - case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; - case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; - case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; - case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; - case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; - case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; - case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; - case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; - case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; + case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; + case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; + case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; + case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; + case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; + case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; + case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; + case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; + case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; + case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; + case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; + case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; + case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; + case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; - case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; - case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; - case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; - case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; - case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; - case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; - case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; - case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; - case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; - case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; - case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; - case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; - case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; - case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; + case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; + case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; + case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; + case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; + case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; + case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; + case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; + case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; + case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; + case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; + case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; + case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; + case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; + case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; - default: { - console.error('Unsupported Format, convert to WebGL internal format failed.'); - return gl.RGBA; - } + default: { + console.error('Unsupported Format, convert to WebGL internal format failed.'); + return gl.RGBA; + } } } export function GFXFormatToWebGLFormat (format: Format, gl: WebGLRenderingContext): GLenum { switch (format) { - case Format.A8: return gl.ALPHA; - case Format.L8: return gl.LUMINANCE; - case Format.LA8: return gl.LUMINANCE_ALPHA; - case Format.RGB8: return gl.RGB; - case Format.RGB16F: return gl.RGB; - case Format.RGB32F: return gl.RGB; - case Format.BGRA8: return gl.RGBA; - case Format.RGBA8: return gl.RGBA; - case Format.RGBA16F: return gl.RGBA; - case Format.RGBA32F: return gl.RGBA; - case Format.R5G6B5: return gl.RGB; - case Format.RGB5A1: return gl.RGBA; - case Format.RGBA4: return gl.RGBA; - case Format.D16: return gl.DEPTH_COMPONENT; - case Format.D16S8: return gl.DEPTH_STENCIL; - case Format.D24: return gl.DEPTH_COMPONENT; - case Format.D24S8: return gl.DEPTH_STENCIL; - case Format.D32F: return gl.DEPTH_COMPONENT; - case Format.D32F_S8: return gl.DEPTH_STENCIL; + case Format.A8: return gl.ALPHA; + case Format.L8: return gl.LUMINANCE; + case Format.LA8: return gl.LUMINANCE_ALPHA; + case Format.RGB8: return gl.RGB; + case Format.RGB16F: return gl.RGB; + case Format.RGB32F: return gl.RGB; + case Format.BGRA8: return gl.RGBA; + case Format.RGBA8: return gl.RGBA; + case Format.RGBA16F: return gl.RGBA; + case Format.RGBA32F: return gl.RGBA; + case Format.R5G6B5: return gl.RGB; + case Format.RGB5A1: return gl.RGBA; + case Format.RGBA4: return gl.RGBA; + case Format.D16: return gl.DEPTH_COMPONENT; + case Format.D16S8: return gl.DEPTH_STENCIL; + case Format.D24: return gl.DEPTH_COMPONENT; + case Format.D24S8: return gl.DEPTH_STENCIL; + case Format.D32F: return gl.DEPTH_COMPONENT; + case Format.D32F_S8: return gl.DEPTH_STENCIL; - case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; - case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; - case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; - case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; - case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; - case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; - case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; - case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; - case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; - case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; - case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; - case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; - case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; - case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; + case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; + case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; + case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; + case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; + case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; + case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; + case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; - case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; - case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; - case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; - case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; - case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; - case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; - case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; - case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; - case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; - case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; - case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; - case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; - case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; - case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; + case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; + case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; + case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; + case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; + case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; + case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; + case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; + case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; + case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; + case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; + case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; + case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; + case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; + case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; - case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; - case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; - case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; - case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; - case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; - case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; - case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; - case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; - case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; - case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; - case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; - case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; - case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; - case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; + case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; + case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; + case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; + case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; + case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; + case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; + case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; + case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; + case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; + case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; + case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; + case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; + case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; + case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; - default: { - console.error('Unsupported Format, convert to WebGL format failed.'); - return gl.RGBA; - } + default: { + console.error('Unsupported Format, convert to WebGL format failed.'); + return gl.RGBA; + } } } function GFXTypeToWebGLType (type: Type, gl: WebGLRenderingContext): GLenum { switch (type) { - case Type.BOOL: return gl.BOOL; - case Type.BOOL2: return gl.BOOL_VEC2; - case Type.BOOL3: return gl.BOOL_VEC3; - case Type.BOOL4: return gl.BOOL_VEC4; - case Type.INT: return gl.INT; - case Type.INT2: return gl.INT_VEC2; - case Type.INT3: return gl.INT_VEC3; - case Type.INT4: return gl.INT_VEC4; - case Type.UINT: return gl.UNSIGNED_INT; - case Type.FLOAT: return gl.FLOAT; - case Type.FLOAT2: return gl.FLOAT_VEC2; - case Type.FLOAT3: return gl.FLOAT_VEC3; - case Type.FLOAT4: return gl.FLOAT_VEC4; - case Type.MAT2: return gl.FLOAT_MAT2; - case Type.MAT3: return gl.FLOAT_MAT3; - case Type.MAT4: return gl.FLOAT_MAT4; - case Type.SAMPLER2D: return gl.SAMPLER_2D; - case Type.SAMPLER_CUBE: return gl.SAMPLER_CUBE; - default: { - console.error('Unsupported GLType, convert to GL type failed.'); - return Type.UNKNOWN; - } + case Type.BOOL: return gl.BOOL; + case Type.BOOL2: return gl.BOOL_VEC2; + case Type.BOOL3: return gl.BOOL_VEC3; + case Type.BOOL4: return gl.BOOL_VEC4; + case Type.INT: return gl.INT; + case Type.INT2: return gl.INT_VEC2; + case Type.INT3: return gl.INT_VEC3; + case Type.INT4: return gl.INT_VEC4; + case Type.UINT: return gl.UNSIGNED_INT; + case Type.FLOAT: return gl.FLOAT; + case Type.FLOAT2: return gl.FLOAT_VEC2; + case Type.FLOAT3: return gl.FLOAT_VEC3; + case Type.FLOAT4: return gl.FLOAT_VEC4; + case Type.MAT2: return gl.FLOAT_MAT2; + case Type.MAT3: return gl.FLOAT_MAT3; + case Type.MAT4: return gl.FLOAT_MAT4; + case Type.SAMPLER2D: return gl.SAMPLER_2D; + case Type.SAMPLER_CUBE: return gl.SAMPLER_CUBE; + default: { + console.error('Unsupported GLType, convert to GL type failed.'); + return Type.UNKNOWN; + } } } function GFXTypeToTypedArrayCtor (type: Type) { switch (type) { - case Type.BOOL: - case Type.BOOL2: - case Type.BOOL3: - case Type.BOOL4: - case Type.INT: - case Type.INT2: - case Type.INT3: - case Type.INT4: - case Type.UINT: - return Int32Array; - case Type.FLOAT: - case Type.FLOAT2: - case Type.FLOAT3: - case Type.FLOAT4: - case Type.MAT2: - case Type.MAT3: - case Type.MAT4: - return Float32Array; - default: { - console.error('Unsupported GLType, convert to TypedArrayConstructor failed.'); - return Float32Array; - } + case Type.BOOL: + case Type.BOOL2: + case Type.BOOL3: + case Type.BOOL4: + case Type.INT: + case Type.INT2: + case Type.INT3: + case Type.INT4: + case Type.UINT: + return Int32Array; + case Type.FLOAT: + case Type.FLOAT2: + case Type.FLOAT3: + case Type.FLOAT4: + case Type.MAT2: + case Type.MAT3: + case Type.MAT4: + return Float32Array; + default: { + console.error('Unsupported GLType, convert to TypedArrayConstructor failed.'); + return Float32Array; + } } } function WebGLTypeToGFXType (glType: GLenum, gl: WebGLRenderingContext): Type { switch (glType) { - case gl.BOOL: return Type.BOOL; - case gl.BOOL_VEC2: return Type.BOOL2; - case gl.BOOL_VEC3: return Type.BOOL3; - case gl.BOOL_VEC4: return Type.BOOL4; - case gl.INT: return Type.INT; - case gl.INT_VEC2: return Type.INT2; - case gl.INT_VEC3: return Type.INT3; - case gl.INT_VEC4: return Type.INT4; - case gl.UNSIGNED_INT: return Type.UINT; - case gl.FLOAT: return Type.FLOAT; - case gl.FLOAT_VEC2: return Type.FLOAT2; - case gl.FLOAT_VEC3: return Type.FLOAT3; - case gl.FLOAT_VEC4: return Type.FLOAT4; - case gl.FLOAT_MAT2: return Type.MAT2; - case gl.FLOAT_MAT3: return Type.MAT3; - case gl.FLOAT_MAT4: return Type.MAT4; - case gl.SAMPLER_2D: return Type.SAMPLER2D; - case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; - default: { - console.error('Unsupported GLType, convert to Type failed.'); - return Type.UNKNOWN; - } + case gl.BOOL: return Type.BOOL; + case gl.BOOL_VEC2: return Type.BOOL2; + case gl.BOOL_VEC3: return Type.BOOL3; + case gl.BOOL_VEC4: return Type.BOOL4; + case gl.INT: return Type.INT; + case gl.INT_VEC2: return Type.INT2; + case gl.INT_VEC3: return Type.INT3; + case gl.INT_VEC4: return Type.INT4; + case gl.UNSIGNED_INT: return Type.UINT; + case gl.FLOAT: return Type.FLOAT; + case gl.FLOAT_VEC2: return Type.FLOAT2; + case gl.FLOAT_VEC3: return Type.FLOAT3; + case gl.FLOAT_VEC4: return Type.FLOAT4; + case gl.FLOAT_MAT2: return Type.MAT2; + case gl.FLOAT_MAT3: return Type.MAT3; + case gl.FLOAT_MAT4: return Type.MAT4; + case gl.SAMPLER_2D: return Type.SAMPLER2D; + case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; + default: { + console.error('Unsupported GLType, convert to Type failed.'); + return Type.UNKNOWN; + } } } function WebGLGetTypeSize (glType: GLenum, gl: WebGLRenderingContext): Type { switch (glType) { - case gl.BOOL: return 4; - case gl.BOOL_VEC2: return 8; - case gl.BOOL_VEC3: return 12; - case gl.BOOL_VEC4: return 16; - case gl.INT: return 4; - case gl.INT_VEC2: return 8; - case gl.INT_VEC3: return 12; - case gl.INT_VEC4: return 16; - case gl.UNSIGNED_INT: return 4; - case gl.FLOAT: return 4; - case gl.FLOAT_VEC2: return 8; - case gl.FLOAT_VEC3: return 12; - case gl.FLOAT_VEC4: return 16; - case gl.FLOAT_MAT2: return 16; - case gl.FLOAT_MAT3: return 36; - case gl.FLOAT_MAT4: return 64; - case gl.SAMPLER_2D: return 4; - case gl.SAMPLER_CUBE: return 4; - default: { - console.error('Unsupported GLType, get type failed.'); - return 0; - } + case gl.BOOL: return 4; + case gl.BOOL_VEC2: return 8; + case gl.BOOL_VEC3: return 12; + case gl.BOOL_VEC4: return 16; + case gl.INT: return 4; + case gl.INT_VEC2: return 8; + case gl.INT_VEC3: return 12; + case gl.INT_VEC4: return 16; + case gl.UNSIGNED_INT: return 4; + case gl.FLOAT: return 4; + case gl.FLOAT_VEC2: return 8; + case gl.FLOAT_VEC3: return 12; + case gl.FLOAT_VEC4: return 16; + case gl.FLOAT_MAT2: return 16; + case gl.FLOAT_MAT3: return 36; + case gl.FLOAT_MAT4: return 64; + case gl.SAMPLER_2D: return 4; + case gl.SAMPLER_CUBE: return 4; + default: { + console.error('Unsupported GLType, get type failed.'); + return 0; + } } } function WebGLGetComponentCount (glType: GLenum, gl: WebGLRenderingContext): Type { switch (glType) { - case gl.FLOAT_MAT2: return 2; - case gl.FLOAT_MAT3: return 3; - case gl.FLOAT_MAT4: return 4; - default: { - return 1; - } + case gl.FLOAT_MAT2: return 2; + case gl.FLOAT_MAT3: return 3; + case gl.FLOAT_MAT4: return 4; + default: { + return 1; + } } } @@ -495,7 +501,8 @@ export enum WebGLCmd { export abstract class WebGLCmdObject { public cmdType: WebGLCmd; - public refCount: number = 0; + + public refCount = 0; constructor (type: WebGLCmd) { this.cmdType = type; @@ -505,14 +512,19 @@ export abstract class WebGLCmdObject { } export class WebGLCmdBeginRenderPass extends WebGLCmdObject { - public gpuRenderPass: IWebGLGPURenderPass | null = null; + public gpuFramebuffer: IWebGLGPUFramebuffer | null = null; + public renderArea = new Rect(); + public clearFlag: ClearFlag = ClearFlag.NONE; + public clearColors: Color[] = []; - public clearDepth: number = 1.0; - public clearStencil: number = 0; + + public clearDepth = 1.0; + + public clearStencil = 0; constructor () { super(WebGLCmd.BEGIN_RENDER_PASS); @@ -525,18 +537,28 @@ export class WebGLCmdBeginRenderPass extends WebGLCmdObject { } export class WebGLCmdBindStates extends WebGLCmdObject { - public gpuPipelineState: IWebGLGPUPipelineState | null = null; + public gpuInputAssembler: IWebGLGPUInputAssembler | null = null; + public gpuDescriptorSets: IWebGLGPUDescriptorSet[] = []; + public dynamicOffsets: number[] = []; + public viewport: Viewport | null = null; + public scissor: Rect | null = null; + public lineWidth: number | null = null; + public depthBias: IWebGLDepthBias | null = null; + public blendConstants: number[] = []; + public depthBounds: IWebGLDepthBounds | null = null; + public stencilWriteMask: IWebGLStencilWriteMask | null = null; + public stencilCompareMask: IWebGLStencilCompareMask | null = null; constructor () { @@ -560,7 +582,6 @@ export class WebGLCmdBindStates extends WebGLCmdObject { } export class WebGLCmdDraw extends WebGLCmdObject { - public drawInfo = new DrawInfo(); constructor () { @@ -572,11 +593,13 @@ export class WebGLCmdDraw extends WebGLCmdObject { } export class WebGLCmdUpdateBuffer extends WebGLCmdObject { - public gpuBuffer: IWebGLGPUBuffer | null = null; + public buffer: BufferSource | null = null; - public offset: number = 0; - public size: number = 0; + + public offset = 0; + + public size = 0; constructor () { super(WebGLCmd.UPDATE_BUFFER); @@ -589,9 +612,10 @@ export class WebGLCmdUpdateBuffer extends WebGLCmdObject { } export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { - public gpuTexture: IWebGLGPUTexture | null = null; + public buffers: ArrayBufferView[] = []; + public regions: BufferTextureCopy[] = []; constructor () { @@ -607,14 +631,18 @@ export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { export class WebGLCmdPackage { public cmds: CachedArray = new CachedArray(1); + public beginRenderPassCmds: CachedArray = new CachedArray(1); + public bindStatesCmds: CachedArray = new CachedArray(1); + public drawCmds: CachedArray = new CachedArray(1); + public updateBufferCmds: CachedArray = new CachedArray(1); + public copyBufferToTextureCmds: CachedArray = new CachedArray(1); public clearCmds (allocator: WebGLCommandAllocator) { - if (this.beginRenderPassCmds.length) { allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds); this.beginRenderPassCmds.clear(); @@ -645,13 +673,11 @@ export class WebGLCmdPackage { } export function WebGLCmdFuncCreateBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer) { - - const gl = device.gl; + const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; if (gpuBuffer.usage & BufferUsageBit.VERTEX) { - gpuBuffer.glTarget = gl.ARRAY_BUFFER; const glBuffer = gl.createBuffer(); if (glBuffer) { @@ -675,7 +701,6 @@ export function WebGLCmdFuncCreateBuffer (device: WebGLDevice, gpuBuffer: IWebGL } } } else if (gpuBuffer.usage & BufferUsageBit.INDEX) { - gpuBuffer.glTarget = gl.ELEMENT_ARRAY_BUFFER; const glBuffer = gl.createBuffer(); @@ -726,8 +751,7 @@ export function WebGLCmdFuncDestroyBuffer (device: WebGLDevice, gpuBuffer: IWebG } export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer) { - - const gl = device.gl; + const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; @@ -774,9 +798,9 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL if (gpuBuffer.buffer) { gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer.buffer); } - } else if ((gpuBuffer.usage & BufferUsageBit.INDIRECT) || - (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) || - (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { + } else if ((gpuBuffer.usage & BufferUsageBit.INDIRECT) + || (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) + || (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { gpuBuffer.glTarget = gl.NONE; } else { console.error('Unsupported BufferType, create buffer failed.'); @@ -785,7 +809,6 @@ export function WebGLCmdFuncResizeBuffer (device: WebGLDevice, gpuBuffer: IWebGL } export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGLGPUBuffer, buffer: BufferSource, offset: number, size: number) { - if (gpuBuffer.usage & BufferUsageBit.UNIFORM) { if (ArrayBuffer.isView(buffer)) { gpuBuffer.vf32!.set(buffer as Float32Array, offset / Float32Array.BYTES_PER_ELEMENT); @@ -797,42 +820,42 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGL Array.prototype.push.apply(gpuBuffer.indirects, (buffer as IndirectBuffer).drawInfos); } else { const buff = buffer as ArrayBuffer; - const gl = device.gl; + const { gl } = device; const cache = device.stateCache; switch (gpuBuffer.glTarget) { - case gl.ARRAY_BUFFER: { - if (device.useVAO) { - if (cache.glVAO) { + case gl.ARRAY_BUFFER: { + if (device.useVAO) { + if (cache.glVAO) { device.OES_vertex_array_object!.bindVertexArrayOES(null); cache.glVAO = gfxStateCache.gpuInputAssembler = null; - } } - - if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer); - device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; - } - break; } - case gl.ELEMENT_ARRAY_BUFFER: { - if (device.useVAO) { - if (cache.glVAO) { + + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; + } + break; + } + case gl.ELEMENT_ARRAY_BUFFER: { + if (device.useVAO) { + if (cache.glVAO) { device.OES_vertex_array_object!.bindVertexArrayOES(null); cache.glVAO = gfxStateCache.gpuInputAssembler = null; - } } + } - if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); - device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; - } - break; - } - default: { - console.error('Unsupported BufferType, update buffer failed.'); - return; + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } + break; + } + default: { + console.error('Unsupported BufferType, update buffer failed.'); + return; + } } if (size === buff.byteLength) { @@ -844,8 +867,7 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLDevice, gpuBuffer: IWebGL } export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture) { - - const gl = device.gl; + const { gl } = device; gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl); @@ -855,136 +877,59 @@ export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWeb let h = gpuTexture.height; switch (gpuTexture.type) { - case TextureType.TEX2D: { - gpuTexture.glTarget = gl.TEXTURE_2D; + case TextureType.TEX2D: { + gpuTexture.glTarget = gl.TEXTURE_2D; - const maxSize = Math.max(w, h); - if (maxSize > device.maxTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); - } - - if (!device.WEBGL_depth_texture && FormatInfos[gpuTexture.format].hasDepth) { - const glRenderbuffer = gl.createRenderbuffer(); - if (glRenderbuffer && gpuTexture.size > 0) { - gpuTexture.glRenderbuffer = glRenderbuffer; - - if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { - gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); - device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; - } - // The internal format here differs from texImage2D convension - if (gpuTexture.glInternalFmt === gl.DEPTH_COMPONENT) { - gpuTexture.glInternalFmt = gl.DEPTH_COMPONENT16; - } - gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h); - } - } else if (gpuTexture.samples === SampleCount.X1) { - const glTexture = gl.createTexture(); - if (glTexture && gpuTexture.size > 0) { - gpuTexture.glTexture = glTexture; - const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; - - if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); - glTexUnit.glTexture = gpuTexture.glTexture; - } - - if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } - else { - // init 2 x 2 texture - const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_2D, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); - } - } - - if (gpuTexture.isPowerOf2) { - gpuTexture.glWrapS = gl.REPEAT; - gpuTexture.glWrapT = gl.REPEAT; - } else { - gpuTexture.glWrapS = gl.CLAMP_TO_EDGE; - gpuTexture.glWrapT = gl.CLAMP_TO_EDGE; - } - gpuTexture.glMinFilter = gl.LINEAR; - gpuTexture.glMagFilter = gl.LINEAR; - - gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS); - gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT); - gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); - gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); - } - else { - gl.deleteTexture(glTexture); - } - } - - break; + const maxSize = Math.max(w, h); + if (maxSize > device.maxTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); } - case TextureType.CUBE: { - gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; - const maxSize = Math.max(w, h); - if (maxSize > device.maxCubeMapTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); + if (!device.WEBGL_depth_texture && FormatInfos[gpuTexture.format].hasDepth) { + const glRenderbuffer = gl.createRenderbuffer(); + if (glRenderbuffer && gpuTexture.size > 0) { + gpuTexture.glRenderbuffer = glRenderbuffer; + + if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); + device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; + } + // The internal format here differs from texImage2D convension + if (gpuTexture.glInternalFmt === gl.DEPTH_COMPONENT) { + gpuTexture.glInternalFmt = gl.DEPTH_COMPONENT16; + } + gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h); } - + } else if (gpuTexture.samples === SampleCount.X1) { const glTexture = gl.createTexture(); if (glTexture && gpuTexture.size > 0) { gpuTexture.glTexture = glTexture; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); glTexUnit.glTexture = gpuTexture.glTexture; } if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, - gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); } } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } - } - else { - for (let f = 0; f < 6; ++f) { - const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); - } - } + // init 2 x 2 texture + const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_2D, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); } if (gpuTexture.isPowerOf2) { @@ -1001,15 +946,85 @@ export function WebGLCmdFuncCreateTexture (device: WebGLDevice, gpuTexture: IWeb gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT); gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); + } else { + gl.deleteTexture(glTexture); + } + } + + break; + } + case TextureType.CUBE: { + gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; + + const maxSize = Math.max(w, h); + if (maxSize > device.maxCubeMapTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); + } + + const glTexture = gl.createTexture(); + if (glTexture && gpuTexture.size > 0) { + gpuTexture.glTexture = glTexture; + const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; } - break; - } - default: { - console.error('Unsupported TextureType, create texture failed.'); - gpuTexture.type = TextureType.TEX2D; - gpuTexture.glTarget = gl.TEXTURE_2D; + if (!FormatInfos[gpuTexture.format].isCompressed) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, + gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } else { + for (let f = 0; f < 6; ++f) { + const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); + } + } + + if (gpuTexture.isPowerOf2) { + gpuTexture.glWrapS = gl.REPEAT; + gpuTexture.glWrapT = gl.REPEAT; + } else { + gpuTexture.glWrapS = gl.CLAMP_TO_EDGE; + gpuTexture.glWrapT = gl.CLAMP_TO_EDGE; + } + gpuTexture.glMinFilter = gl.LINEAR; + gpuTexture.glMagFilter = gl.LINEAR; + + gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS); + gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT); + gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); + gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); } + + break; + } + default: { + console.error('Unsupported TextureType, create texture failed.'); + gpuTexture.type = TextureType.TEX2D; + gpuTexture.glTarget = gl.TEXTURE_2D; + } } } @@ -1026,8 +1041,7 @@ export function WebGLCmdFuncDestroyTexture (device: WebGLDevice, gpuTexture: IWe } export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWebGLGPUTexture) { - - const gl = device.gl; + const { gl } = device; gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl); @@ -1037,102 +1051,99 @@ export function WebGLCmdFuncResizeTexture (device: WebGLDevice, gpuTexture: IWeb let h = gpuTexture.height; switch (gpuTexture.type) { - case TextureType.TEX2D: { - gpuTexture.glTarget = gl.TEXTURE_2D; + case TextureType.TEX2D: { + gpuTexture.glTarget = gl.TEXTURE_2D; - const maxSize = Math.max(w, h); - if (maxSize > device.maxTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); - } - - if (gpuTexture.glRenderbuffer) { - if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { - gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); - device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; - } - gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h); - } else if (gpuTexture.glTexture) { - const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; - - if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); - glTexUnit.glTexture = gpuTexture.glTexture; - } - - if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } - } - } - break; + const maxSize = Math.max(w, h); + if (maxSize > device.maxTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); } - case TextureType.CUBE: { - gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; - const maxSize = Math.max(w, h); - if (maxSize > device.maxCubeMapTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); + if (gpuTexture.glRenderbuffer) { + if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); + device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; } - + gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h); + } else if (gpuTexture.glTexture) { const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); glTexUnit.glTexture = gpuTexture.glTexture; } if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); } - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); } } - break; } - default: { - console.error('Unsupported TextureType, create texture failed.'); - gpuTexture.type = TextureType.TEX2D; - gpuTexture.glTarget = gl.TEXTURE_2D; + break; + } + case TextureType.CUBE: { + gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; + + const maxSize = Math.max(w, h); + if (maxSize > device.maxCubeMapTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); } + + const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + if (!FormatInfos[gpuTexture.format].isCompressed) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, + 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } + break; + } + default: { + console.error('Unsupported TextureType, create texture failed.'); + gpuTexture.type = TextureType.TEX2D; + gpuTexture.glTarget = gl.TEXTURE_2D; + } } } export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuffer: IWebGLGPUFramebuffer) { if (!gpuFramebuffer.gpuColorTextures.length && !gpuFramebuffer.gpuDepthStencilTexture) { return; } // onscreen fbo - const gl = device.gl; + const { gl } = device; const attachments: GLenum[] = []; const glFramebuffer = gl.createFramebuffer(); @@ -1144,7 +1155,6 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuff } for (let i = 0; i < gpuFramebuffer.gpuColorTextures.length; ++i) { - const gpuTexture = gpuFramebuffer.gpuColorTextures[i]; if (gpuTexture) { if (gpuTexture.glTexture) { @@ -1153,7 +1163,8 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuff gl.COLOR_ATTACHMENT0 + i, gpuTexture.glTarget, gpuTexture.glTexture, - 0); // level must be 0 + 0, + ); // level must be 0 } else { gl.framebufferRenderbuffer( gl.FRAMEBUFFER, @@ -1176,7 +1187,8 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuff glAttachment, dst.glTarget, dst.glTexture, - 0); // level must be 0 + 0, + ); // level must be 0 } else { gl.framebufferRenderbuffer( gl.FRAMEBUFFER, @@ -1194,23 +1206,23 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLDevice, gpuFramebuff const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status !== gl.FRAMEBUFFER_COMPLETE) { switch (status) { - case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); - break; - } - case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); - break; - } - case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); - break; - } - case gl.FRAMEBUFFER_UNSUPPORTED: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); - break; - } - default: + case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); + break; + } + case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); + break; + } + case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); + break; + } + case gl.FRAMEBUFFER_UNSUPPORTED: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); + break; + } + default: } } @@ -1228,7 +1240,7 @@ export function WebGLCmdFuncDestroyFramebuffer (device: WebGLDevice, gpuFramebuf } export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGLGPUShader) { - const gl = device.gl; + const { gl } = device; for (let k = 0; k < gpuShader.gpuStages.length; k++) { const gpuStage = gpuShader.gpuStages[k]; @@ -1238,20 +1250,20 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL let lineNumber = 1; switch (gpuStage.type) { - case ShaderStageFlagBit.VERTEX: { - shaderTypeStr = 'VertexShader'; - glShaderType = gl.VERTEX_SHADER; - break; - } - case ShaderStageFlagBit.FRAGMENT: { - shaderTypeStr = 'FragmentShader'; - glShaderType = gl.FRAGMENT_SHADER; - break; - } - default: { - console.error('Unsupported ShaderType.'); - return; - } + case ShaderStageFlagBit.VERTEX: { + shaderTypeStr = 'VertexShader'; + glShaderType = gl.VERTEX_SHADER; + break; + } + case ShaderStageFlagBit.FRAGMENT: { + shaderTypeStr = 'FragmentShader'; + glShaderType = gl.FRAGMENT_SHADER; + break; + } + default: { + console.error('Unsupported ShaderType.'); + return; + } } const glShader = gl.createShader(glShaderType); @@ -1261,7 +1273,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL gl.compileShader(gpuStage.glShader); if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { - console.error(shaderTypeStr + ' in \'' + gpuShader.name + '\' compilation failed.'); + console.error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, () => `\n${lineNumber++} `)); console.error(gl.getShaderInfoLog(gpuStage.glShader)); @@ -1305,9 +1317,9 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL } if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { - console.info('Shader \'' + gpuShader.name + '\' compilation succeeded.'); + console.info(`Shader '${gpuShader.name}' compilation succeeded.`); } else { - console.error('Failed to link shader \'' + gpuShader.name + '\'.'); + console.error(`Failed to link shader '${gpuShader.name}'.`); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); return; } @@ -1444,11 +1456,10 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL for (let i = 0; i < activeUniformCount; ++i) { const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); if (uniformInfo) { - const isSampler = (uniformInfo.type === gl.SAMPLER_2D) || - (uniformInfo.type === gl.SAMPLER_CUBE); + const isSampler = (uniformInfo.type === gl.SAMPLER_2D) + || (uniformInfo.type === gl.SAMPLER_CUBE); if (!isSampler) { - const glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name); if (glLoc !== null) { let varName: string; @@ -1485,8 +1496,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL // texture unit index mapping optimization const glActiveSamplers: IWebGLGPUUniformSampler[] = []; const glActiveSamplerLocations: WebGLUniformLocation[] = []; - const bindingMappingInfo = device.bindingMappingInfo; - const texUnitCacheMap = device.stateCache.texUnitCacheMap; + const { bindingMappingInfo } = device; + const { texUnitCacheMap } = device.stateCache; let flexibleSetBaseOffset = 0; for (let i = 0; i < gpuShader.blocks.length; ++i) { @@ -1505,7 +1516,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL } if (texUnitCacheMap[sampler.name] === undefined) { let binding = sampler.binding + bindingMappingInfo.samplerOffsets[sampler.set] + arrayOffset; - if (sampler.set === bindingMappingInfo.flexibleSet) binding -= flexibleSetBaseOffset; + if (sampler.set === bindingMappingInfo.flexibleSet) { binding -= flexibleSetBaseOffset; } texUnitCacheMap[sampler.name] = binding % device.maxTextureUnits; arrayOffset += sampler.count - 1; } @@ -1579,7 +1590,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLDevice, gpuShader: IWebGL export function WebGLCmdFuncDestroyShader (device: WebGLDevice, gpuShader: IWebGLGPUShader) { if (gpuShader.glProgram) { - const gl = device.gl; + const { gl } = device; if (!device.destroyShadersImmediately) { for (let k = 0; k < gpuShader.gpuStages.length; k++) { const gpuStage = gpuShader.gpuStages[k]; @@ -1596,8 +1607,7 @@ export function WebGLCmdFuncDestroyShader (device: WebGLDevice, gpuShader: IWebG } export function WebGLCmdFuncCreateInputAssember (device: WebGLDevice, gpuInputAssembler: IWebGLGPUInputAssembler) { - - const gl = device.gl; + const { gl } = device; gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length); @@ -1611,7 +1621,7 @@ export function WebGLCmdFuncCreateInputAssember (device: WebGLDevice, gpuInputAs const gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; const glType = GFXFormatToWebGLType(attrib.format, gl); - const size = FormatInfos[attrib.format].size; + const { size } = FormatInfos[attrib.format]; gpuInputAssembler.glAttribs[i] = { name: attrib.name, @@ -1660,9 +1670,9 @@ export function WebGLCmdFuncBeginRenderPass ( renderArea: Rect, clearColors: Color[], clearDepth: number, - clearStencil: number) { - - const gl = device.gl; + clearStencil: number, +) { + const { gl } = device; const cache = device.stateCache; let clears: GLbitfield = 0; @@ -1680,11 +1690,10 @@ export function WebGLCmdFuncBeginRenderPass ( } } - if (cache.viewport.left !== renderArea.x || - cache.viewport.top !== renderArea.y || - cache.viewport.width !== renderArea.width || - cache.viewport.height !== renderArea.height) { - + if (cache.viewport.left !== renderArea.x + || cache.viewport.top !== renderArea.y + || cache.viewport.width !== renderArea.width + || cache.viewport.height !== renderArea.height) { gl.viewport(renderArea.x, renderArea.y, renderArea.width, renderArea.height); cache.viewport.left = renderArea.x; @@ -1693,11 +1702,10 @@ export function WebGLCmdFuncBeginRenderPass ( cache.viewport.height = renderArea.height; } - if (cache.scissorRect.x !== renderArea.x || - cache.scissorRect.y !== renderArea.y || - cache.scissorRect.width !== renderArea.width || - cache.scissorRect.height !== renderArea.height) { - + if (cache.scissorRect.x !== renderArea.x + || cache.scissorRect.y !== renderArea.y + || cache.scissorRect.width !== renderArea.width + || cache.scissorRect.height !== renderArea.height) { gl.scissor(renderArea.x, renderArea.y, renderArea.width, renderArea.height); cache.scissorRect.x = renderArea.x; @@ -1718,72 +1726,71 @@ export function WebGLCmdFuncBeginRenderPass ( if (colorAttachment.format !== Format.UNKNOWN) { switch (colorAttachment.loadOp) { - case LoadOp.LOAD: break; // GL default behavior - case LoadOp.CLEAR: { - if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) { - gl.colorMask(true, true, true, true); - } + case LoadOp.LOAD: break; // GL default behavior + case LoadOp.CLEAR: { + if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) { + gl.colorMask(true, true, true, true); + } - const clearColor = clearColors[0]; - gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w); - clears |= gl.COLOR_BUFFER_BIT; - break; - } - case LoadOp.DISCARD: { - // invalidate the framebuffer - // invalidateAttachments.push(gl.COLOR_ATTACHMENT0 + j); - break; - } - default: + const clearColor = clearColors[0]; + gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w); + clears |= gl.COLOR_BUFFER_BIT; + break; + } + case LoadOp.DISCARD: { + // invalidate the framebuffer + // invalidateAttachments.push(gl.COLOR_ATTACHMENT0 + j); + break; + } + default: } } } // if (curGPURenderPass) if (gpuRenderPass.depthStencilAttachment) { - if (gpuRenderPass.depthStencilAttachment.format !== Format.UNKNOWN) { switch (gpuRenderPass.depthStencilAttachment.depthLoadOp) { - case LoadOp.LOAD: break; // GL default behavior - case LoadOp.CLEAR: { - if (!cache.dss.depthWrite) { - gl.depthMask(true); - } - - gl.clearDepth(clearDepth); - - clears |= gl.DEPTH_BUFFER_BIT; - break; + case LoadOp.LOAD: break; // GL default behavior + case LoadOp.CLEAR: { + if (!cache.dss.depthWrite) { + gl.depthMask(true); } - case LoadOp.DISCARD: { - // invalidate the framebuffer - // invalidateAttachments.push(gl.DEPTH_ATTACHMENT); - break; - } - default: + + gl.clearDepth(clearDepth); + + clears |= gl.DEPTH_BUFFER_BIT; + break; + } + case LoadOp.DISCARD: { + // invalidate the framebuffer + // invalidateAttachments.push(gl.DEPTH_ATTACHMENT); + break; + } + default: } if (FormatInfos[gpuRenderPass.depthStencilAttachment.format].hasStencil) { switch (gpuRenderPass.depthStencilAttachment.stencilLoadOp) { - case LoadOp.LOAD: break; // GL default behavior - case LoadOp.CLEAR: { - if (!cache.dss.stencilWriteMaskFront) { - gl.stencilMaskSeparate(gl.FRONT, 0xffff); - } - - if (!cache.dss.stencilWriteMaskBack) { - gl.stencilMaskSeparate(gl.BACK, 0xffff); - } - - gl.clearStencil(clearStencil); - clears |= gl.STENCIL_BUFFER_BIT; - break; + case LoadOp.LOAD: break; // GL default behavior + case LoadOp.CLEAR: { + if (!cache.dss.stencilWriteMaskFront) { + gl.stencilMaskSeparate(gl.FRONT, 0xffff); } - case LoadOp.DISCARD: { - // invalidate the framebuffer - // invalidateAttachments.push(gl.STENCIL_ATTACHMENT); - break; + + if (!cache.dss.stencilWriteMaskBack) { + gl.stencilMaskSeparate(gl.BACK, 0xffff); } - default: + + gl.clearStencil(clearStencil); + clears |= gl.STENCIL_BUFFER_BIT; + break; + } + case LoadOp.DISCARD: { + // invalidate the framebuffer + // invalidateAttachments.push(gl.STENCIL_ATTACHMENT); + break; + } + default: } } } @@ -1801,7 +1808,6 @@ export function WebGLCmdFuncBeginRenderPass ( // restore states if (clears & gl.COLOR_BUFFER_BIT) { - const colorMask = cache.bs.targets[0].blendColorMask; if (colorMask !== ColorMask.ALL) { const r = (colorMask & ColorMask.R) !== ColorMask.NONE; @@ -1812,8 +1818,8 @@ export function WebGLCmdFuncBeginRenderPass ( } } - if ((clears & gl.DEPTH_BUFFER_BIT) && - !cache.dss.depthWrite) { + if ((clears & gl.DEPTH_BUFFER_BIT) + && !cache.dss.depthWrite) { gl.depthMask(false); } @@ -1842,9 +1848,9 @@ export function WebGLCmdFuncBindStates ( blendConstants: number[], depthBounds: IWebGLDepthBounds | null, stencilWriteMask: IWebGLStencilWriteMask | null, - stencilCompareMask: IWebGLStencilCompareMask | null) { - - const gl = device.gl; + stencilCompareMask: IWebGLStencilCompareMask | null, +) { + const { gl } = device; const cache = device.stateCache; const gpuShader = gpuPipelineState && gpuPipelineState.gpuShader; @@ -1859,8 +1865,7 @@ export function WebGLCmdFuncBindStates ( gfxStateCache.glPrimitive = gpuPipelineState.glPrimitive; if (gpuPipelineState.gpuShader) { - - const glProgram = gpuPipelineState.gpuShader.glProgram; + const { glProgram } = gpuPipelineState.gpuShader; if (cache.glProgram !== glProgram) { gl.useProgram(glProgram); cache.glProgram = glProgram; @@ -1869,26 +1874,25 @@ export function WebGLCmdFuncBindStates ( } // rasterizer state - const rs = gpuPipelineState.rs; + const { rs } = gpuPipelineState; if (rs) { - if (cache.rs.cullMode !== rs.cullMode) { switch (rs.cullMode) { - case CullMode.NONE: { - gl.disable(gl.CULL_FACE); - break; - } - case CullMode.FRONT: { - gl.enable(gl.CULL_FACE); - gl.cullFace(gl.FRONT); - break; - } - case CullMode.BACK: { - gl.enable(gl.CULL_FACE); - gl.cullFace(gl.BACK); - break; - } - default: + case CullMode.NONE: { + gl.disable(gl.CULL_FACE); + break; + } + case CullMode.FRONT: { + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.FRONT); + break; + } + case CullMode.BACK: { + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.BACK); + break; + } + default: } cache.rs.cullMode = rs.cullMode; @@ -1900,8 +1904,8 @@ export function WebGLCmdFuncBindStates ( cache.rs.isFrontFaceCCW = isFrontFaceCCW; } - if ((cache.rs.depthBias !== rs.depthBias) || - (cache.rs.depthBiasSlop !== rs.depthBiasSlop)) { + if ((cache.rs.depthBias !== rs.depthBias) + || (cache.rs.depthBiasSlop !== rs.depthBiasSlop)) { gl.polygonOffset(rs.depthBias, rs.depthBiasSlop); cache.rs.depthBias = rs.depthBias; cache.rs.depthBiasSlop = rs.depthBiasSlop; @@ -1911,13 +1915,11 @@ export function WebGLCmdFuncBindStates ( gl.lineWidth(rs.lineWidth); cache.rs.lineWidth = rs.lineWidth; } - } // rasterizater state // depth-stencil state - const dss = gpuPipelineState.dss; + const { dss } = gpuPipelineState; if (dss) { - if (cache.dss.depthTest !== dss.depthTest) { if (dss.depthTest) { gl.enable(gl.DEPTH_TEST); @@ -1938,8 +1940,8 @@ export function WebGLCmdFuncBindStates ( } // front - if ((cache.dss.stencilTestFront !== dss.stencilTestFront) || - (cache.dss.stencilTestBack !== dss.stencilTestBack)) { + if ((cache.dss.stencilTestFront !== dss.stencilTestFront) + || (cache.dss.stencilTestBack !== dss.stencilTestBack)) { if (dss.stencilTestFront || dss.stencilTestBack) { gl.enable(gl.STENCIL_TEST); } else { @@ -1949,30 +1951,30 @@ export function WebGLCmdFuncBindStates ( cache.dss.stencilTestBack = dss.stencilTestBack; } - if ((cache.dss.stencilFuncFront !== dss.stencilFuncFront) || - (cache.dss.stencilRefFront !== dss.stencilRefFront) || - (cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront)) { - + if ((cache.dss.stencilFuncFront !== dss.stencilFuncFront) + || (cache.dss.stencilRefFront !== dss.stencilRefFront) + || (cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront)) { gl.stencilFuncSeparate( gl.FRONT, WebGLCmpFuncs[dss.stencilFuncFront], dss.stencilRefFront, - dss.stencilReadMaskFront); + dss.stencilReadMaskFront, + ); cache.dss.stencilFuncFront = dss.stencilFuncFront; cache.dss.stencilRefFront = dss.stencilRefFront; cache.dss.stencilReadMaskFront = dss.stencilReadMaskFront; } - if ((cache.dss.stencilFailOpFront !== dss.stencilFailOpFront) || - (cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront) || - (cache.dss.stencilPassOpFront !== dss.stencilPassOpFront)) { - + if ((cache.dss.stencilFailOpFront !== dss.stencilFailOpFront) + || (cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront) + || (cache.dss.stencilPassOpFront !== dss.stencilPassOpFront)) { gl.stencilOpSeparate( gl.FRONT, WebGLStencilOps[dss.stencilFailOpFront], WebGLStencilOps[dss.stencilZFailOpFront], - WebGLStencilOps[dss.stencilPassOpFront]); + WebGLStencilOps[dss.stencilPassOpFront], + ); cache.dss.stencilFailOpFront = dss.stencilFailOpFront; cache.dss.stencilZFailOpFront = dss.stencilZFailOpFront; @@ -1985,30 +1987,30 @@ export function WebGLCmdFuncBindStates ( } // back - if ((cache.dss.stencilFuncBack !== dss.stencilFuncBack) || - (cache.dss.stencilRefBack !== dss.stencilRefBack) || - (cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack)) { - + if ((cache.dss.stencilFuncBack !== dss.stencilFuncBack) + || (cache.dss.stencilRefBack !== dss.stencilRefBack) + || (cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack)) { gl.stencilFuncSeparate( gl.BACK, WebGLCmpFuncs[dss.stencilFuncBack], dss.stencilRefBack, - dss.stencilReadMaskBack); + dss.stencilReadMaskBack, + ); cache.dss.stencilFuncBack = dss.stencilFuncBack; cache.dss.stencilRefBack = dss.stencilRefBack; cache.dss.stencilReadMaskBack = dss.stencilReadMaskBack; } - if ((cache.dss.stencilFailOpBack !== dss.stencilFailOpBack) || - (cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack) || - (cache.dss.stencilPassOpBack !== dss.stencilPassOpBack)) { - + if ((cache.dss.stencilFailOpBack !== dss.stencilFailOpBack) + || (cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack) + || (cache.dss.stencilPassOpBack !== dss.stencilPassOpBack)) { gl.stencilOpSeparate( gl.BACK, WebGLStencilOps[dss.stencilFailOpBack], WebGLStencilOps[dss.stencilZFailOpBack], - WebGLStencilOps[dss.stencilPassOpBack]); + WebGLStencilOps[dss.stencilPassOpBack], + ); cache.dss.stencilFailOpBack = dss.stencilFailOpBack; cache.dss.stencilZFailOpBack = dss.stencilZFailOpBack; @@ -2022,9 +2024,8 @@ export function WebGLCmdFuncBindStates ( } // depth-stencil state // blend state - const bs = gpuPipelineState.bs; + const { bs } = gpuPipelineState; if (bs) { - if (cache.bs.isA2C !== bs.isA2C) { if (bs.isA2C) { gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE); @@ -2034,11 +2035,10 @@ export function WebGLCmdFuncBindStates ( cache.bs.isA2C = bs.isA2C; } - if ((cache.bs.blendColor.x !== bs.blendColor.x) || - (cache.bs.blendColor.y !== bs.blendColor.y) || - (cache.bs.blendColor.z !== bs.blendColor.z) || - (cache.bs.blendColor.w !== bs.blendColor.w)) { - + if ((cache.bs.blendColor.x !== bs.blendColor.x) + || (cache.bs.blendColor.y !== bs.blendColor.y) + || (cache.bs.blendColor.z !== bs.blendColor.z) + || (cache.bs.blendColor.w !== bs.blendColor.w)) { gl.blendColor(bs.blendColor.x, bs.blendColor.y, bs.blendColor.z, bs.blendColor.w); cache.bs.blendColor.x = bs.blendColor.x; @@ -2059,23 +2059,23 @@ export function WebGLCmdFuncBindStates ( target0Cache.blend = target0.blend; } - if ((target0Cache.blendEq !== target0.blendEq) || - (target0Cache.blendAlphaEq !== target0.blendAlphaEq)) { + if ((target0Cache.blendEq !== target0.blendEq) + || (target0Cache.blendAlphaEq !== target0.blendAlphaEq)) { gl.blendEquationSeparate(WebGLBlendOps[target0.blendEq], WebGLBlendOps[target0.blendAlphaEq]); target0Cache.blendEq = target0.blendEq; target0Cache.blendAlphaEq = target0.blendAlphaEq; } - if ((target0Cache.blendSrc !== target0.blendSrc) || - (target0Cache.blendDst !== target0.blendDst) || - (target0Cache.blendSrcAlpha !== target0.blendSrcAlpha) || - (target0Cache.blendDstAlpha !== target0.blendDstAlpha)) { - + if ((target0Cache.blendSrc !== target0.blendSrc) + || (target0Cache.blendDst !== target0.blendDst) + || (target0Cache.blendSrcAlpha !== target0.blendSrcAlpha) + || (target0Cache.blendDstAlpha !== target0.blendDstAlpha)) { gl.blendFuncSeparate( WebGLBlendFactors[target0.blendSrc], WebGLBlendFactors[target0.blendDst], WebGLBlendFactors[target0.blendSrcAlpha], - WebGLBlendFactors[target0.blendDstAlpha]); + WebGLBlendFactors[target0.blendDstAlpha], + ); target0Cache.blendSrc = target0.blendSrc; target0Cache.blendDst = target0.blendDst; @@ -2084,12 +2084,12 @@ export function WebGLCmdFuncBindStates ( } if (target0Cache.blendColorMask !== target0.blendColorMask) { - gl.colorMask( (target0.blendColorMask & ColorMask.R) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.G) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.B) !== ColorMask.NONE, - (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE); + (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE, + ); target0Cache.blendColorMask = target0.blendColorMask; } @@ -2098,9 +2098,8 @@ export function WebGLCmdFuncBindStates ( // bind descriptor sets if (gpuPipelineState && gpuPipelineState.gpuPipelineLayout && gpuShader) { - const blockLen = gpuShader.glBlocks.length; - const dynamicOffsetIndices = gpuPipelineState.gpuPipelineLayout.dynamicOffsetIndices; + const { dynamicOffsetIndices } = gpuPipelineState.gpuPipelineLayout; for (let j = 0; j < blockLen; j++) { const glBlock = gpuShader.glBlocks[j]; @@ -2110,10 +2109,10 @@ export function WebGLCmdFuncBindStates ( let vf32: Float32Array | null = null; let offset = 0; if (gpuDescriptor && gpuDescriptor.gpuBuffer) { - const gpuBuffer = gpuDescriptor.gpuBuffer; + const { gpuBuffer } = gpuDescriptor; const dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set]; const dynamicOffsetIndex = dynamicOffsetIndexSet && dynamicOffsetIndexSet[glBlock.binding]; - if (dynamicOffsetIndex >= 0) offset = dynamicOffsets[dynamicOffsetIndex]; + if (dynamicOffsetIndex >= 0) { offset = dynamicOffsets[dynamicOffsetIndex]; } if ('vf32' in gpuBuffer) { vf32 = gpuBuffer.vf32; @@ -2133,154 +2132,154 @@ export function WebGLCmdFuncBindStates ( for (let l = 0; l < uniformLen; l++) { const glUniform = glBlock.glActiveUniforms[l]; switch (glUniform.glType) { - case gl.BOOL: - case gl.INT: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform1iv(glUniform.glLoc, glUniform.array as Int32Array); - break; + case gl.BOOL: + case gl.INT: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform1iv(glUniform.glLoc, glUniform.array as Int32Array); + break; } - break; } - case gl.BOOL_VEC2: - case gl.INT_VEC2: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform2iv(glUniform.glLoc, glUniform.array as Int32Array); - break; + break; + } + case gl.BOOL_VEC2: + case gl.INT_VEC2: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform2iv(glUniform.glLoc, glUniform.array as Int32Array); + break; } - break; } - case gl.BOOL_VEC3: - case gl.INT_VEC3: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform3iv(glUniform.glLoc, glUniform.array as Int32Array); - break; + break; + } + case gl.BOOL_VEC3: + case gl.INT_VEC3: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform3iv(glUniform.glLoc, glUniform.array as Int32Array); + break; } - break; } - case gl.BOOL_VEC4: - case gl.INT_VEC4: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform4iv(glUniform.glLoc, glUniform.array as Int32Array); - break; + break; + } + case gl.BOOL_VEC4: + case gl.INT_VEC4: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform4iv(glUniform.glLoc, glUniform.array as Int32Array); + break; } - break; } - case gl.FLOAT: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform1fv(glUniform.glLoc, glUniform.array as Float32Array); - break; + break; + } + case gl.FLOAT: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform1fv(glUniform.glLoc, glUniform.array as Float32Array); + break; } - break; } - case gl.FLOAT_VEC2: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform2fv(glUniform.glLoc, glUniform.array as Float32Array); - break; + break; + } + case gl.FLOAT_VEC2: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform2fv(glUniform.glLoc, glUniform.array as Float32Array); + break; } - break; } - case gl.FLOAT_VEC3: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform3fv(glUniform.glLoc, glUniform.array as Float32Array); - break; + break; + } + case gl.FLOAT_VEC3: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform3fv(glUniform.glLoc, glUniform.array as Float32Array); + break; } - break; } - case gl.FLOAT_VEC4: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniform4fv(glUniform.glLoc, glUniform.array as Float32Array); - break; + break; + } + case gl.FLOAT_VEC4: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniform4fv(glUniform.glLoc, glUniform.array as Float32Array); + break; } - break; } - case gl.FLOAT_MAT2: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array as Float32Array); - break; + break; + } + case gl.FLOAT_MAT2: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array as Float32Array); + break; } - break; } - case gl.FLOAT_MAT3: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array as Float32Array); - break; + break; + } + case gl.FLOAT_MAT3: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array as Float32Array); + break; } - break; } - case gl.FLOAT_MAT4: { - for (let u = 0; u < glUniform.array.length; ++u) { - const idx = glUniform.begin + offset + u; - if (vf32[idx] !== glUniform.array[u]) { - for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { - glUniform.array[n] = vf32[m]; - } - gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array as Float32Array); - break; + break; + } + case gl.FLOAT_MAT4: { + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + offset + u; + if (vf32[idx] !== glUniform.array[u]) { + for (let n = u, m = idx; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = vf32[m]; } + gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array as Float32Array); + break; } - break; } - default: + break; + } + default: } } continue; @@ -2302,10 +2301,9 @@ export function WebGLCmdFuncBindStates ( continue; } - if (gpuDescriptor.gpuTexture && - gpuDescriptor.gpuTexture.size > 0) { - - const gpuTexture = gpuDescriptor.gpuTexture; + if (gpuDescriptor.gpuTexture + && gpuDescriptor.gpuTexture.size > 0) { + const { gpuTexture } = gpuDescriptor; const glTexUnit = cache.glTexUnits[texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { @@ -2321,7 +2319,7 @@ export function WebGLCmdFuncBindStates ( glTexUnit.glTexture = gpuTexture.glTexture; } - const gpuSampler = gpuDescriptor.gpuSampler; + const { gpuSampler } = gpuDescriptor; if (gpuTexture.isPowerOf2) { glWrapS = gpuSampler.glWrapS; glWrapT = gpuSampler.glWrapT; @@ -2331,21 +2329,19 @@ export function WebGLCmdFuncBindStates ( } if (gpuTexture.isPowerOf2) { - if (gpuTexture.mipLevel <= 1 && - (gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || - gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR)) { + if (gpuTexture.mipLevel <= 1 + && (gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST + || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR)) { glMinFilter = gl.LINEAR; } else { glMinFilter = gpuSampler.glMinFilter; } + } else if (gpuSampler.glMinFilter === gl.LINEAR + || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST + || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR) { + glMinFilter = gl.LINEAR; } else { - if (gpuSampler.glMinFilter === gl.LINEAR || - gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || - gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR) { - glMinFilter = gl.LINEAR; - } else { - glMinFilter = gl.NEAREST; - } + glMinFilter = gl.NEAREST; } if (gpuTexture.glWrapS !== glWrapS) { @@ -2391,8 +2387,8 @@ export function WebGLCmdFuncBindStates ( } // bind descriptor sets // bind vertex/index buffer - if (gpuInputAssembler && gpuShader && - (isShaderChanged || gfxStateCache.gpuInputAssembler !== gpuInputAssembler)) { + if (gpuInputAssembler && gpuShader + && (isShaderChanged || gfxStateCache.gpuInputAssembler !== gpuInputAssembler)) { gfxStateCache.gpuInputAssembler = gpuInputAssembler; const ia = device.ANGLE_instanced_arrays; @@ -2525,162 +2521,160 @@ export function WebGLCmdFuncBindStates ( for (let j = 0; j < dsLen; j++) { const dynamicState = gpuPipelineState.dynamicStates[j]; switch (dynamicState) { - case DynamicStateFlagBit.VIEWPORT: { - if (viewport) { - if (cache.viewport.left !== viewport.left || - cache.viewport.top !== viewport.top || - cache.viewport.width !== viewport.width || - cache.viewport.height !== viewport.height) { + case DynamicStateFlagBit.VIEWPORT: { + if (viewport) { + if (cache.viewport.left !== viewport.left + || cache.viewport.top !== viewport.top + || cache.viewport.width !== viewport.width + || cache.viewport.height !== viewport.height) { + gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height); - gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height); + cache.viewport.left = viewport.left; + cache.viewport.top = viewport.top; + cache.viewport.width = viewport.width; + cache.viewport.height = viewport.height; + } + } + break; + } + case DynamicStateFlagBit.SCISSOR: { + if (scissor) { + if (cache.scissorRect.x !== scissor.x + || cache.scissorRect.y !== scissor.y + || cache.scissorRect.width !== scissor.width + || cache.scissorRect.height !== scissor.height) { + gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height); - cache.viewport.left = viewport.left; - cache.viewport.top = viewport.top; - cache.viewport.width = viewport.width; - cache.viewport.height = viewport.height; + cache.scissorRect.x = scissor.x; + cache.scissorRect.y = scissor.y; + cache.scissorRect.width = scissor.width; + cache.scissorRect.height = scissor.height; + } + } + break; + } + case DynamicStateFlagBit.LINE_WIDTH: { + if (lineWidth) { + if (cache.rs.lineWidth !== lineWidth) { + gl.lineWidth(lineWidth); + cache.rs.lineWidth = lineWidth; + } + } + break; + } + case DynamicStateFlagBit.DEPTH_BIAS: { + if (depthBias) { + if ((cache.rs.depthBias !== depthBias.constantFactor) + || (cache.rs.depthBiasSlop !== depthBias.slopeFactor)) { + gl.polygonOffset(depthBias.constantFactor, depthBias.slopeFactor); + cache.rs.depthBias = depthBias.constantFactor; + cache.rs.depthBiasSlop = depthBias.slopeFactor; + } + } + break; + } + case DynamicStateFlagBit.BLEND_CONSTANTS: { + if ((cache.bs.blendColor.x !== blendConstants[0]) + || (cache.bs.blendColor.y !== blendConstants[1]) + || (cache.bs.blendColor.z !== blendConstants[2]) + || (cache.bs.blendColor.w !== blendConstants[3])) { + gl.blendColor(blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]); + [cache.bs.blendColor.x, cache.bs.blendColor.y, cache.bs.blendColor.z, cache.bs.blendColor.w] = blendConstants; + } + break; + } + case DynamicStateFlagBit.STENCIL_WRITE_MASK: { + if (stencilWriteMask) { + switch (stencilWriteMask.face) { + case StencilFace.FRONT: { + if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(gl.FRONT, stencilWriteMask.writeMask); + cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; } + break; } - break; - } - case DynamicStateFlagBit.SCISSOR: { - if (scissor) { - if (cache.scissorRect.x !== scissor.x || - cache.scissorRect.y !== scissor.y || - cache.scissorRect.width !== scissor.width || - cache.scissorRect.height !== scissor.height) { - - gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height); - - cache.scissorRect.x = scissor.x; - cache.scissorRect.y = scissor.y; - cache.scissorRect.width = scissor.width; - cache.scissorRect.height = scissor.height; + case StencilFace.BACK: { + if (cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(gl.BACK, stencilWriteMask.writeMask); + cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; } + break; } - break; - } - case DynamicStateFlagBit.LINE_WIDTH: { - if (lineWidth) { - if (cache.rs.lineWidth !== lineWidth) { - gl.lineWidth(lineWidth); - cache.rs.lineWidth = lineWidth; + case StencilFace.ALL: { + if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask + || cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { + gl.stencilMask(stencilWriteMask.writeMask); + cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; + cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; } + break; + } + default: } - break; } - case DynamicStateFlagBit.DEPTH_BIAS: { - if (depthBias) { - - if ((cache.rs.depthBias !== depthBias.constantFactor) || - (cache.rs.depthBiasSlop !== depthBias.slopeFactor)) { - gl.polygonOffset(depthBias.constantFactor, depthBias.slopeFactor); - cache.rs.depthBias = depthBias.constantFactor; - cache.rs.depthBiasSlop = depthBias.slopeFactor; + break; + } + case DynamicStateFlagBit.STENCIL_COMPARE_MASK: { + if (stencilCompareMask) { + switch (stencilCompareMask.face) { + case StencilFace.FRONT: { + if (cache.dss.stencilRefFront !== stencilCompareMask.reference + || cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + gl.FRONT, + WebGLCmpFuncs[cache.dss.stencilFuncFront], + stencilCompareMask.reference, + stencilCompareMask.compareMask, + ); + cache.dss.stencilRefFront = stencilCompareMask.reference; + cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; } + break; } - break; - } - case DynamicStateFlagBit.BLEND_CONSTANTS: { - if ((cache.bs.blendColor.x !== blendConstants[0]) || - (cache.bs.blendColor.y !== blendConstants[1]) || - (cache.bs.blendColor.z !== blendConstants[2]) || - (cache.bs.blendColor.w !== blendConstants[3])) { - - gl.blendColor(blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]); - - cache.bs.blendColor.x = blendConstants[0]; - cache.bs.blendColor.y = blendConstants[1]; - cache.bs.blendColor.z = blendConstants[2]; - cache.bs.blendColor.w = blendConstants[3]; - } - break; - } - case DynamicStateFlagBit.STENCIL_WRITE_MASK: { - if (stencilWriteMask) { - switch (stencilWriteMask.face) { - case StencilFace.FRONT: { - if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask) { - gl.stencilMaskSeparate(gl.FRONT, stencilWriteMask.writeMask); - cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; - } - break; - } - case StencilFace.BACK: { - if (cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { - gl.stencilMaskSeparate(gl.BACK, stencilWriteMask.writeMask); - cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; - } - break; - } - case StencilFace.ALL: { - if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask || - cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { - gl.stencilMask(stencilWriteMask.writeMask); - cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; - cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; - } - break; - } + case StencilFace.BACK: { + if (cache.dss.stencilRefBack !== stencilCompareMask.reference + || cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + gl.BACK, + WebGLCmpFuncs[cache.dss.stencilFuncBack], + stencilCompareMask.reference, + stencilCompareMask.compareMask, + ); + cache.dss.stencilRefBack = stencilCompareMask.reference; + cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; } + break; } - break; - } - case DynamicStateFlagBit.STENCIL_COMPARE_MASK: { - if (stencilCompareMask) { - switch (stencilCompareMask.face) { - case StencilFace.FRONT: { - if (cache.dss.stencilRefFront !== stencilCompareMask.reference || - cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask) { - gl.stencilFuncSeparate( - gl.FRONT, - WebGLCmpFuncs[cache.dss.stencilFuncFront], - stencilCompareMask.reference, - stencilCompareMask.compareMask); - cache.dss.stencilRefFront = stencilCompareMask.reference; - cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; - } - break; - } - case StencilFace.BACK: { - if (cache.dss.stencilRefBack !== stencilCompareMask.reference || - cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { - gl.stencilFuncSeparate( - gl.BACK, - WebGLCmpFuncs[cache.dss.stencilFuncBack], - stencilCompareMask.reference, - stencilCompareMask.compareMask); - cache.dss.stencilRefBack = stencilCompareMask.reference; - cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; - } - break; - } - case StencilFace.ALL: { - if (cache.dss.stencilRefFront !== stencilCompareMask.reference || - cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask || - cache.dss.stencilRefBack !== stencilCompareMask.reference || - cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { - gl.stencilFunc( - WebGLCmpFuncs[cache.dss.stencilFuncBack], - stencilCompareMask.reference, - stencilCompareMask.compareMask); - cache.dss.stencilRefFront = stencilCompareMask.reference; - cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; - cache.dss.stencilRefBack = stencilCompareMask.reference; - cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; - } - break; - } + case StencilFace.ALL: { + if (cache.dss.stencilRefFront !== stencilCompareMask.reference + || cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask + || cache.dss.stencilRefBack !== stencilCompareMask.reference + || cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { + gl.stencilFunc( + WebGLCmpFuncs[cache.dss.stencilFuncBack], + stencilCompareMask.reference, + stencilCompareMask.compareMask, + ); + cache.dss.stencilRefFront = stencilCompareMask.reference; + cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; + cache.dss.stencilRefBack = stencilCompareMask.reference; + cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; } + break; + } + default: } - break; } + break; + } + default: } // switch } // for } // update dynamic states } export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: DrawInfo) { - const gl = device.gl; + const { gl } = device; const ia = device.ANGLE_instanced_arrays; const { gpuInputAssembler, glPrimitive } = gfxStateCache; @@ -2700,15 +2694,13 @@ export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: DrawInfo) { } else if (subDrawInfo.vertexCount > 0) { ia.drawArraysInstancedANGLE(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount, subDrawInfo.instanceCount); } - } else { - if (gpuBuffer) { - if (subDrawInfo.indexCount > 0) { - const offset = subDrawInfo.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, subDrawInfo.indexCount, gpuInputAssembler.glIndexType, offset); - } - } else if (subDrawInfo.vertexCount > 0) { - gl.drawArrays(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount); + } else if (gpuBuffer) { + if (subDrawInfo.indexCount > 0) { + const offset = subDrawInfo.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, subDrawInfo.indexCount, gpuInputAssembler.glIndexType, offset); } + } else if (subDrawInfo.vertexCount > 0) { + gl.drawArrays(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount); } } } else { @@ -2723,15 +2715,13 @@ export function WebGLCmdFuncDraw (device: WebGLDevice, drawInfo: DrawInfo) { } else if (drawInfo.vertexCount > 0) { ia.drawArraysInstancedANGLE(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount); } - } else { - if (gpuBuffer) { - if (drawInfo.indexCount > 0) { - const offset = drawInfo.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); - } - } else if (drawInfo.vertexCount > 0) { - gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount); + } else if (gpuBuffer) { + if (drawInfo.indexCount > 0) { + const offset = drawInfo.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); } + } else if (drawInfo.vertexCount > 0) { + gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount); } } } @@ -2746,41 +2736,42 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLDevice, cmdPackage: WebGLC const cmdId = cmdIds[cmd]++; switch (cmd) { - case WebGLCmd.BEGIN_RENDER_PASS: { - const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; - WebGLCmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, - cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil); - break; - } - /* + case WebGLCmd.BEGIN_RENDER_PASS: { + const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; + WebGLCmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, + cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil); + break; + } + /* case WebGLCmd.END_RENDER_PASS: { // WebGL 1.0 doesn't support store operation of attachments. // StoreOp.Store is the default GL behavior. break; } */ - case WebGLCmd.BIND_STATES: { - const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; - WebGLCmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, - cmd2.viewport, cmd2.scissor, cmd2.lineWidth, cmd2.depthBias, cmd2.blendConstants, - cmd2.depthBounds, cmd2.stencilWriteMask, cmd2.stencilCompareMask); - break; - } - case WebGLCmd.DRAW: { - const cmd3 = cmdPackage.drawCmds.array[cmdId]; - WebGLCmdFuncDraw(device, cmd3.drawInfo); - break; - } - case WebGLCmd.UPDATE_BUFFER: { - const cmd4 = cmdPackage.updateBufferCmds.array[cmdId]; - WebGLCmdFuncUpdateBuffer(device, cmd4.gpuBuffer as IWebGLGPUBuffer, cmd4.buffer as BufferSource, cmd4.offset, cmd4.size); - break; - } - case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { - const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; - WebGLCmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture as IWebGLGPUTexture, cmd5.regions); - break; - } + case WebGLCmd.BIND_STATES: { + const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; + WebGLCmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, + cmd2.viewport, cmd2.scissor, cmd2.lineWidth, cmd2.depthBias, cmd2.blendConstants, + cmd2.depthBounds, cmd2.stencilWriteMask, cmd2.stencilCompareMask); + break; + } + case WebGLCmd.DRAW: { + const cmd3 = cmdPackage.drawCmds.array[cmdId]; + WebGLCmdFuncDraw(device, cmd3.drawInfo); + break; + } + case WebGLCmd.UPDATE_BUFFER: { + const cmd4 = cmdPackage.updateBufferCmds.array[cmdId]; + WebGLCmdFuncUpdateBuffer(device, cmd4.gpuBuffer as IWebGLGPUBuffer, cmd4.buffer as BufferSource, cmd4.offset, cmd4.size); + break; + } + case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { + const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; + WebGLCmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture as IWebGLGPUTexture, cmd5.regions); + break; + } + default: } // switch } // for } @@ -2789,9 +2780,9 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( device: WebGLDevice, texImages: TexImageSource[], gpuTexture: IWebGLGPUTexture, - regions: BufferTextureCopy[]) { - - const gl = device.gl; + regions: BufferTextureCopy[], +) { + const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture); @@ -2802,36 +2793,36 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( let f = 0; switch (gpuTexture.glTarget) { - case gl.TEXTURE_2D: { - for (let i = 0; i < regions.length; i++) { - const region = regions[i]; - // console.debug('Copying image to texture 2D: ' + region.texExtent.width + ' x ' + region.texExtent.height); - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + case gl.TEXTURE_2D: { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; + // console.debug('Copying image to texture 2D: ' + region.texExtent.width + ' x ' + region.texExtent.height); + gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, + gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + } + break; + } + case gl.TEXTURE_CUBE_MAP: { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; + // console.debug('Copying image to texture cube: ' + region.texExtent.width + ' x ' + region.texExtent.height); + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { + gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); } - break; - } - case gl.TEXTURE_CUBE_MAP: { - for (let i = 0; i < regions.length; i++) { - const region = regions[i]; - // console.debug('Copying image to texture cube: ' + region.texExtent.width + ' x ' + region.texExtent.height); - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, - gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); - } - } - break; - } - default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); } + break; + } + default: { + console.error('Unsupported GL texture type, copy buffer to texture failed.'); + } } - if ((gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) && - gpuTexture.isPowerOf2) { + if ((gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) + && gpuTexture.isPowerOf2) { gl.generateMipmap(gpuTexture.glTarget); } } @@ -2840,9 +2831,9 @@ export function WebGLCmdFuncCopyBuffersToTexture ( device: WebGLDevice, buffers: ArrayBufferView[], gpuTexture: IWebGLGPUTexture, - regions: BufferTextureCopy[]) { - - const gl = device.gl; + regions: BufferTextureCopy[], +) { + const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture); @@ -2855,65 +2846,61 @@ export function WebGLCmdFuncCopyBuffersToTexture ( let f = 0; const fmtInfo: FormatInfo = FormatInfos[gpuTexture.format]; - const isCompressed = fmtInfo.isCompressed; + const { isCompressed } = fmtInfo; switch (gpuTexture.glTarget) { - case gl.TEXTURE_2D: { - for (let i = 0; i < regions.length; i++) { - const region = regions[i]; + case gl.TEXTURE_2D: { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; + w = region.texExtent.width; + h = region.texExtent.height; + // console.debug('Copying buffer to texture 2D: ' + w + ' x ' + h); + + const pixels = buffers[n++]; + if (!isCompressed) { + gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + } else if (gpuTexture.glInternalFmt === WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL || device.noCompressedTexSubImage2D) { + gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + gpuTexture.glInternalFmt, w, h, 0, pixels); + } else { + gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + } + } + + break; + } + case gl.TEXTURE_CUBE_MAP: { + for (let i = 0; i < regions.length; i++) { + const region = regions[i]; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { w = region.texExtent.width; h = region.texExtent.height; - // console.debug('Copying buffer to texture 2D: ' + w + ' x ' + h); + // console.debug('Copying buffer to texture cube: ' + w + ' x ' + h); const pixels = buffers[n++]; if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, gpuTexture.glType, pixels); + } else if (gpuTexture.glInternalFmt === WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL || device.noCompressedTexSubImage2D) { + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, + gpuTexture.glInternalFmt, w, h, 0, pixels); } else { - if (gpuTexture.glInternalFmt === WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL || device.noCompressedTexSubImage2D) { - gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); - } else { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - } + gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); } } - - break; - } - case gl.TEXTURE_CUBE_MAP: { - for (let i = 0; i < regions.length; i++) { - const region = regions[i]; - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - // console.debug('Copying buffer to texture cube: ' + w + ' x ' + h); - - const pixels = buffers[n++]; - if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); - } else { - if (gpuTexture.glInternalFmt === WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL || device.noCompressedTexSubImage2D) { - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); - } else { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - } - } - } - } - break; - } - default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); } + break; + } + default: { + console.error('Unsupported GL texture type, copy buffer to texture failed.'); + } } if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) { diff --git a/cocos/core/gfx/webgl/webgl-device.ts b/cocos/core/gfx/webgl/webgl-device.ts index 0c5d93b404..d13c2982a6 100644 --- a/cocos/core/gfx/webgl/webgl-device.ts +++ b/cocos/core/gfx/webgl/webgl-device.ts @@ -359,7 +359,7 @@ export class WebGLDevice extends Device { // earlier runtime VAO implementations doesn't work if (RUNTIME_BASED && !VIVO) { - // @ts-ignore + // @ts-expect-error if (typeof loadRuntime !== 'function' || !loadRuntime() || typeof loadRuntime().getFeature !== 'function' || loadRuntime() .getFeature('webgl.extensions.oes_vertex_array_object.revision') <= 0) { this._OES_vertex_array_object = null; diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index 5aae7f951a..d98bf99893 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -20,7 +20,9 @@ import { Type, FormatInfo, } from '../define'; -import { Color, Rect, Viewport, BufferTextureCopy } from '../define-class'; +import { + Color, Rect, Viewport, BufferTextureCopy, +} from '../define-class'; import { WebGLEXT } from '../webgl/webgl-define'; import { WebGL2CommandAllocator } from './webgl2-command-allocator'; import { @@ -67,8 +69,6 @@ const SAMPLES: number[] = [ const _f32v4 = new Float32Array(4); -// tslint:disable: max-line-length - function CmpF32NotEuqal (a: number, b: number): boolean { const c = a - b; return (c > 0.000001 || c < -0.000001); @@ -76,516 +76,513 @@ function CmpF32NotEuqal (a: number, b: number): boolean { export function GFXFormatToWebGLType (format: Format, gl: WebGL2RenderingContext): GLenum { switch (format) { - case Format.R8: return gl.UNSIGNED_BYTE; - case Format.R8SN: return gl.BYTE; - case Format.R8UI: return gl.UNSIGNED_BYTE; - case Format.R8I: return gl.BYTE; - case Format.R16F: return gl.HALF_FLOAT; - case Format.R16UI: return gl.UNSIGNED_SHORT; - case Format.R16I: return gl.SHORT; - case Format.R32F: return gl.FLOAT; - case Format.R32UI: return gl.UNSIGNED_INT; - case Format.R32I: return gl.INT; + case Format.R8: return gl.UNSIGNED_BYTE; + case Format.R8SN: return gl.BYTE; + case Format.R8UI: return gl.UNSIGNED_BYTE; + case Format.R8I: return gl.BYTE; + case Format.R16F: return gl.HALF_FLOAT; + case Format.R16UI: return gl.UNSIGNED_SHORT; + case Format.R16I: return gl.SHORT; + case Format.R32F: return gl.FLOAT; + case Format.R32UI: return gl.UNSIGNED_INT; + case Format.R32I: return gl.INT; - case Format.RG8: return gl.UNSIGNED_BYTE; - case Format.RG8SN: return gl.BYTE; - case Format.RG8UI: return gl.UNSIGNED_BYTE; - case Format.RG8I: return gl.BYTE; - case Format.RG16F: return gl.HALF_FLOAT; - case Format.RG16UI: return gl.UNSIGNED_SHORT; - case Format.RG16I: return gl.SHORT; - case Format.RG32F: return gl.FLOAT; - case Format.RG32UI: return gl.UNSIGNED_INT; - case Format.RG32I: return gl.INT; + case Format.RG8: return gl.UNSIGNED_BYTE; + case Format.RG8SN: return gl.BYTE; + case Format.RG8UI: return gl.UNSIGNED_BYTE; + case Format.RG8I: return gl.BYTE; + case Format.RG16F: return gl.HALF_FLOAT; + case Format.RG16UI: return gl.UNSIGNED_SHORT; + case Format.RG16I: return gl.SHORT; + case Format.RG32F: return gl.FLOAT; + case Format.RG32UI: return gl.UNSIGNED_INT; + case Format.RG32I: return gl.INT; - case Format.RGB8: return gl.UNSIGNED_BYTE; - case Format.SRGB8: return gl.UNSIGNED_BYTE; - case Format.RGB8SN: return gl.BYTE; - case Format.RGB8UI: return gl.UNSIGNED_BYTE; - case Format.RGB8I: return gl.BYTE; - case Format.RGB16F: return gl.HALF_FLOAT; - case Format.RGB16UI: return gl.UNSIGNED_SHORT; - case Format.RGB16I: return gl.SHORT; - case Format.RGB32F: return gl.FLOAT; - case Format.RGB32UI: return gl.UNSIGNED_INT; - case Format.RGB32I: return gl.INT; + case Format.RGB8: return gl.UNSIGNED_BYTE; + case Format.SRGB8: return gl.UNSIGNED_BYTE; + case Format.RGB8SN: return gl.BYTE; + case Format.RGB8UI: return gl.UNSIGNED_BYTE; + case Format.RGB8I: return gl.BYTE; + case Format.RGB16F: return gl.HALF_FLOAT; + case Format.RGB16UI: return gl.UNSIGNED_SHORT; + case Format.RGB16I: return gl.SHORT; + case Format.RGB32F: return gl.FLOAT; + case Format.RGB32UI: return gl.UNSIGNED_INT; + case Format.RGB32I: return gl.INT; - case Format.BGRA8: return gl.UNSIGNED_BYTE; - case Format.RGBA8: return gl.UNSIGNED_BYTE; - case Format.SRGB8_A8: return gl.UNSIGNED_BYTE; - case Format.RGBA8SN: return gl.BYTE; - case Format.RGBA8UI: return gl.UNSIGNED_BYTE; - case Format.RGBA8I: return gl.BYTE; - case Format.RGBA16F: return gl.HALF_FLOAT; - case Format.RGBA16UI: return gl.UNSIGNED_SHORT; - case Format.RGBA16I: return gl.SHORT; - case Format.RGBA32F: return gl.FLOAT; - case Format.RGBA32UI: return gl.UNSIGNED_INT; - case Format.RGBA32I: return gl.INT; + case Format.BGRA8: return gl.UNSIGNED_BYTE; + case Format.RGBA8: return gl.UNSIGNED_BYTE; + case Format.SRGB8_A8: return gl.UNSIGNED_BYTE; + case Format.RGBA8SN: return gl.BYTE; + case Format.RGBA8UI: return gl.UNSIGNED_BYTE; + case Format.RGBA8I: return gl.BYTE; + case Format.RGBA16F: return gl.HALF_FLOAT; + case Format.RGBA16UI: return gl.UNSIGNED_SHORT; + case Format.RGBA16I: return gl.SHORT; + case Format.RGBA32F: return gl.FLOAT; + case Format.RGBA32UI: return gl.UNSIGNED_INT; + case Format.RGBA32I: return gl.INT; - case Format.R5G6B5: return gl.UNSIGNED_SHORT_5_6_5; - case Format.R11G11B10F: return gl.UNSIGNED_INT_10F_11F_11F_REV; - case Format.RGB5A1: return gl.UNSIGNED_SHORT_5_5_5_1; - case Format.RGBA4: return gl.UNSIGNED_SHORT_4_4_4_4; - case Format.RGB10A2: return gl.UNSIGNED_INT_2_10_10_10_REV; - case Format.RGB10A2UI: return gl.UNSIGNED_INT_2_10_10_10_REV; - case Format.RGB9E5: return gl.FLOAT; + case Format.R5G6B5: return gl.UNSIGNED_SHORT_5_6_5; + case Format.R11G11B10F: return gl.UNSIGNED_INT_10F_11F_11F_REV; + case Format.RGB5A1: return gl.UNSIGNED_SHORT_5_5_5_1; + case Format.RGBA4: return gl.UNSIGNED_SHORT_4_4_4_4; + case Format.RGB10A2: return gl.UNSIGNED_INT_2_10_10_10_REV; + case Format.RGB10A2UI: return gl.UNSIGNED_INT_2_10_10_10_REV; + case Format.RGB9E5: return gl.FLOAT; - case Format.D16: return gl.UNSIGNED_SHORT; - case Format.D16S8: return gl.UNSIGNED_INT_24_8; // no D16S8 support - case Format.D24: return gl.UNSIGNED_INT; - case Format.D24S8: return gl.UNSIGNED_INT_24_8; - case Format.D32F: return gl.FLOAT; - case Format.D32F_S8: return gl.FLOAT_32_UNSIGNED_INT_24_8_REV; + case Format.D16: return gl.UNSIGNED_SHORT; + case Format.D16S8: return gl.UNSIGNED_INT_24_8; // no D16S8 support + case Format.D24: return gl.UNSIGNED_INT; + case Format.D24S8: return gl.UNSIGNED_INT_24_8; + case Format.D32F: return gl.FLOAT; + case Format.D32F_S8: return gl.FLOAT_32_UNSIGNED_INT_24_8_REV; - case Format.BC1: return gl.UNSIGNED_BYTE; - case Format.BC1_SRGB: return gl.UNSIGNED_BYTE; - case Format.BC2: return gl.UNSIGNED_BYTE; - case Format.BC2_SRGB: return gl.UNSIGNED_BYTE; - case Format.BC3: return gl.UNSIGNED_BYTE; - case Format.BC3_SRGB: return gl.UNSIGNED_BYTE; - case Format.BC4: return gl.UNSIGNED_BYTE; - case Format.BC4_SNORM: return gl.BYTE; - case Format.BC5: return gl.UNSIGNED_BYTE; - case Format.BC5_SNORM: return gl.BYTE; - case Format.BC6H_SF16: return gl.FLOAT; - case Format.BC6H_UF16: return gl.FLOAT; - case Format.BC7: return gl.UNSIGNED_BYTE; - case Format.BC7_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC1: return gl.UNSIGNED_BYTE; + case Format.BC1_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC2: return gl.UNSIGNED_BYTE; + case Format.BC2_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC3: return gl.UNSIGNED_BYTE; + case Format.BC3_SRGB: return gl.UNSIGNED_BYTE; + case Format.BC4: return gl.UNSIGNED_BYTE; + case Format.BC4_SNORM: return gl.BYTE; + case Format.BC5: return gl.UNSIGNED_BYTE; + case Format.BC5_SNORM: return gl.BYTE; + case Format.BC6H_SF16: return gl.FLOAT; + case Format.BC6H_UF16: return gl.FLOAT; + case Format.BC7: return gl.UNSIGNED_BYTE; + case Format.BC7_SRGB: return gl.UNSIGNED_BYTE; - case Format.ETC_RGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_RGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_SRGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_RGB8_A1: return gl.UNSIGNED_BYTE; - case Format.ETC2_SRGB8_A1: return gl.UNSIGNED_BYTE; - case Format.ETC2_RGB8: return gl.UNSIGNED_BYTE; - case Format.ETC2_SRGB8: return gl.UNSIGNED_BYTE; - case Format.EAC_R11: return gl.UNSIGNED_BYTE; - case Format.EAC_R11SN: return gl.BYTE; - case Format.EAC_RG11: return gl.UNSIGNED_BYTE; - case Format.EAC_RG11SN: return gl.BYTE; + case Format.ETC_RGB8: return gl.UNSIGNED_BYTE; + case Format.ETC2_RGB8: return gl.UNSIGNED_BYTE; + case Format.ETC2_SRGB8: return gl.UNSIGNED_BYTE; + case Format.ETC2_RGB8_A1: return gl.UNSIGNED_BYTE; + case Format.ETC2_SRGB8_A1: return gl.UNSIGNED_BYTE; + case Format.EAC_R11: return gl.UNSIGNED_BYTE; + case Format.EAC_R11SN: return gl.BYTE; + case Format.EAC_RG11: return gl.UNSIGNED_BYTE; + case Format.EAC_RG11SN: return gl.BYTE; - case Format.PVRTC_RGB2: return gl.UNSIGNED_BYTE; - case Format.PVRTC_RGBA2: return gl.UNSIGNED_BYTE; - case Format.PVRTC_RGB4: return gl.UNSIGNED_BYTE; - case Format.PVRTC_RGBA4: return gl.UNSIGNED_BYTE; - case Format.PVRTC2_2BPP: return gl.UNSIGNED_BYTE; - case Format.PVRTC2_4BPP: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGB2: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGBA2: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGB4: return gl.UNSIGNED_BYTE; + case Format.PVRTC_RGBA4: return gl.UNSIGNED_BYTE; + case Format.PVRTC2_2BPP: return gl.UNSIGNED_BYTE; + case Format.PVRTC2_4BPP: return gl.UNSIGNED_BYTE; - case Format.ASTC_RGBA_4x4: - case Format.ASTC_RGBA_5x4: - case Format.ASTC_RGBA_5x5: - case Format.ASTC_RGBA_6x5: - case Format.ASTC_RGBA_6x6: - case Format.ASTC_RGBA_8x5: - case Format.ASTC_RGBA_8x6: - case Format.ASTC_RGBA_8x8: - case Format.ASTC_RGBA_10x5: - case Format.ASTC_RGBA_10x6: - case Format.ASTC_RGBA_10x8: - case Format.ASTC_RGBA_10x10: - case Format.ASTC_RGBA_12x10: - case Format.ASTC_RGBA_12x12: - case Format.ASTC_SRGBA_4x4: - case Format.ASTC_SRGBA_5x4: - case Format.ASTC_SRGBA_5x5: - case Format.ASTC_SRGBA_6x5: - case Format.ASTC_SRGBA_6x6: - case Format.ASTC_SRGBA_8x5: - case Format.ASTC_SRGBA_8x6: - case Format.ASTC_SRGBA_8x8: - case Format.ASTC_SRGBA_10x5: - case Format.ASTC_SRGBA_10x6: - case Format.ASTC_SRGBA_10x8: - case Format.ASTC_SRGBA_10x10: - case Format.ASTC_SRGBA_12x10: - case Format.ASTC_SRGBA_12x12: - return gl.UNSIGNED_BYTE; + case Format.ASTC_RGBA_4x4: + case Format.ASTC_RGBA_5x4: + case Format.ASTC_RGBA_5x5: + case Format.ASTC_RGBA_6x5: + case Format.ASTC_RGBA_6x6: + case Format.ASTC_RGBA_8x5: + case Format.ASTC_RGBA_8x6: + case Format.ASTC_RGBA_8x8: + case Format.ASTC_RGBA_10x5: + case Format.ASTC_RGBA_10x6: + case Format.ASTC_RGBA_10x8: + case Format.ASTC_RGBA_10x10: + case Format.ASTC_RGBA_12x10: + case Format.ASTC_RGBA_12x12: + case Format.ASTC_SRGBA_4x4: + case Format.ASTC_SRGBA_5x4: + case Format.ASTC_SRGBA_5x5: + case Format.ASTC_SRGBA_6x5: + case Format.ASTC_SRGBA_6x6: + case Format.ASTC_SRGBA_8x5: + case Format.ASTC_SRGBA_8x6: + case Format.ASTC_SRGBA_8x8: + case Format.ASTC_SRGBA_10x5: + case Format.ASTC_SRGBA_10x6: + case Format.ASTC_SRGBA_10x8: + case Format.ASTC_SRGBA_10x10: + case Format.ASTC_SRGBA_12x10: + case Format.ASTC_SRGBA_12x12: + return gl.UNSIGNED_BYTE; - default: { - return gl.UNSIGNED_BYTE; - } + default: { + return gl.UNSIGNED_BYTE; + } } } export function GFXFormatToWebGLInternalFormat (format: Format, gl: WebGL2RenderingContext): GLenum { switch (format) { - case Format.A8: return gl.ALPHA; - case Format.L8: return gl.LUMINANCE; - case Format.LA8: return gl.LUMINANCE_ALPHA; - case Format.R8: return gl.R8; - case Format.R8SN: return gl.R8_SNORM; - case Format.R8UI: return gl.R8UI; - case Format.R8I: return gl.R8I; - case Format.RG8: return gl.RG8; - case Format.RG8SN: return gl.RG8_SNORM; - case Format.RG8UI: return gl.RG8UI; - case Format.RG8I: return gl.RG8I; - case Format.RGB8: return gl.RGB8; - case Format.RGB8SN: return gl.RGB8_SNORM; - case Format.RGB8UI: return gl.RGB8UI; - case Format.RGB8I: return gl.RGB8I; - case Format.BGRA8: return gl.RGBA8; - case Format.RGBA8: return gl.RGBA8; - case Format.RGBA8SN: return gl.RGBA8_SNORM; - case Format.RGBA8UI: return gl.RGBA8UI; - case Format.RGBA8I: return gl.RGBA8I; - case Format.R16I: return gl.R16I; - case Format.R16UI: return gl.R16UI; - case Format.R16F: return gl.R16F; - case Format.RG16I: return gl.RG16I; - case Format.RG16UI: return gl.RG16UI; - case Format.RG16F: return gl.RG16F; - case Format.RGB16I: return gl.RGB16I; - case Format.RGB16UI: return gl.RGB16UI; - case Format.RGB16F: return gl.RGB16F; - case Format.RGBA16I: return gl.RGBA16I; - case Format.RGBA16UI: return gl.RGBA16UI; - case Format.RGBA16F: return gl.RGBA16F; - case Format.R32I: return gl.R32I; - case Format.R32UI: return gl.R32UI; - case Format.R32F: return gl.R32F; - case Format.RG32I: return gl.RG32I; - case Format.RG32UI: return gl.RG32UI; - case Format.RG32F: return gl.RG32F; - case Format.RGB32I: return gl.RGB32I; - case Format.RGB32UI: return gl.RGB32UI; - case Format.RGB32F: return gl.RGB32F; - case Format.RGBA32I: return gl.RGBA32I; - case Format.RGBA32UI: return gl.RGBA32UI; - case Format.RGBA32F: return gl.RGBA32F; - case Format.R5G6B5: return gl.RGB565; - case Format.RGB5A1: return gl.RGB5_A1; - case Format.RGBA4: return gl.RGBA4; - case Format.RGB10A2: return gl.RGB10_A2; - case Format.RGB10A2UI: return gl.RGB10_A2UI; - case Format.R11G11B10F: return gl.R11F_G11F_B10F; - case Format.D16: return gl.DEPTH_COMPONENT16; - case Format.D16S8: return gl.DEPTH24_STENCIL8; // no D16S8 support - case Format.D24: return gl.DEPTH_COMPONENT24; - case Format.D24S8: return gl.DEPTH24_STENCIL8; - case Format.D32F: return gl.DEPTH_COMPONENT32F; - case Format.D32F_S8: return gl.DEPTH32F_STENCIL8; + case Format.A8: return gl.ALPHA; + case Format.L8: return gl.LUMINANCE; + case Format.LA8: return gl.LUMINANCE_ALPHA; + case Format.R8: return gl.R8; + case Format.R8SN: return gl.R8_SNORM; + case Format.R8UI: return gl.R8UI; + case Format.R8I: return gl.R8I; + case Format.RG8: return gl.RG8; + case Format.RG8SN: return gl.RG8_SNORM; + case Format.RG8UI: return gl.RG8UI; + case Format.RG8I: return gl.RG8I; + case Format.RGB8: return gl.RGB8; + case Format.RGB8SN: return gl.RGB8_SNORM; + case Format.RGB8UI: return gl.RGB8UI; + case Format.RGB8I: return gl.RGB8I; + case Format.BGRA8: return gl.RGBA8; + case Format.RGBA8: return gl.RGBA8; + case Format.RGBA8SN: return gl.RGBA8_SNORM; + case Format.RGBA8UI: return gl.RGBA8UI; + case Format.RGBA8I: return gl.RGBA8I; + case Format.R16I: return gl.R16I; + case Format.R16UI: return gl.R16UI; + case Format.R16F: return gl.R16F; + case Format.RG16I: return gl.RG16I; + case Format.RG16UI: return gl.RG16UI; + case Format.RG16F: return gl.RG16F; + case Format.RGB16I: return gl.RGB16I; + case Format.RGB16UI: return gl.RGB16UI; + case Format.RGB16F: return gl.RGB16F; + case Format.RGBA16I: return gl.RGBA16I; + case Format.RGBA16UI: return gl.RGBA16UI; + case Format.RGBA16F: return gl.RGBA16F; + case Format.R32I: return gl.R32I; + case Format.R32UI: return gl.R32UI; + case Format.R32F: return gl.R32F; + case Format.RG32I: return gl.RG32I; + case Format.RG32UI: return gl.RG32UI; + case Format.RG32F: return gl.RG32F; + case Format.RGB32I: return gl.RGB32I; + case Format.RGB32UI: return gl.RGB32UI; + case Format.RGB32F: return gl.RGB32F; + case Format.RGBA32I: return gl.RGBA32I; + case Format.RGBA32UI: return gl.RGBA32UI; + case Format.RGBA32F: return gl.RGBA32F; + case Format.R5G6B5: return gl.RGB565; + case Format.RGB5A1: return gl.RGB5_A1; + case Format.RGBA4: return gl.RGBA4; + case Format.RGB10A2: return gl.RGB10_A2; + case Format.RGB10A2UI: return gl.RGB10_A2UI; + case Format.R11G11B10F: return gl.R11F_G11F_B10F; + case Format.D16: return gl.DEPTH_COMPONENT16; + case Format.D16S8: return gl.DEPTH24_STENCIL8; // no D16S8 support + case Format.D24: return gl.DEPTH_COMPONENT24; + case Format.D24S8: return gl.DEPTH24_STENCIL8; + case Format.D32F: return gl.DEPTH_COMPONENT32F; + case Format.D32F_S8: return gl.DEPTH32F_STENCIL8; - case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; - case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; - case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; - case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; - case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; - case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; - case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; - case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; - case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; - case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; - case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; - case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; - case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; - case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; + case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; + case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; + case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; + case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; + case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; + case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; + case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; - case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; - case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; - case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; - case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; - case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; - case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; - case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; - case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; - case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; - case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; - case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; - case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; - case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; - case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; + case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; + case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; + case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; + case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; + case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; + case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; + case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; + case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; + case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; + case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; + case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; + case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; + case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; + case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; - case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; - case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; - case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; - case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; - case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; - case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; - case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; - case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; - case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; - case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; - case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; - case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; - case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; - case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; + case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; + case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; + case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; + case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; + case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; + case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; + case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; + case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; + case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; + case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; + case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; + case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; + case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; + case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; - default: { - console.error('Unsupported Format, convert to WebGL internal format failed.'); - return gl.RGBA; - } + default: { + console.error('Unsupported Format, convert to WebGL internal format failed.'); + return gl.RGBA; + } } } export function GFXFormatToWebGLFormat (format: Format, gl: WebGL2RenderingContext): GLenum { switch (format) { - case Format.A8: return gl.ALPHA; - case Format.L8: return gl.LUMINANCE; - case Format.LA8: return gl.LUMINANCE_ALPHA; - case Format.R8: - case Format.R8SN: return gl.RED; - case Format.R8UI: - case Format.R8I: return gl.RED; - case Format.RG8: - case Format.RG8SN: - case Format.RG8UI: - case Format.RG8I: return gl.RG; - case Format.RGB8: - case Format.RGB8SN: - case Format.RGB8UI: - case Format.RGB8I: return gl.RGB; - case Format.BGRA8: - case Format.RGBA8: - case Format.RGBA8SN: - case Format.RGBA8UI: - case Format.RGBA8I: return gl.RGBA; - case Format.R16UI: - case Format.R16I: - case Format.R16F: return gl.RED; - case Format.RG16UI: - case Format.RG16I: - case Format.RG16F: return gl.RG; - case Format.RGB16UI: - case Format.RGB16I: - case Format.RGB16F: return gl.RGB; - case Format.RGBA16UI: - case Format.RGBA16I: - case Format.RGBA16F: return gl.RGBA; - case Format.R32UI: - case Format.R32I: - case Format.R32F: return gl.RED; - case Format.RG32UI: - case Format.RG32I: - case Format.RG32F: return gl.RG; - case Format.RGB32UI: - case Format.RGB32I: - case Format.RGB32F: return gl.RGB; - case Format.RGBA32UI: - case Format.RGBA32I: - case Format.RGBA32F: return gl.RGBA; - case Format.RGB10A2: return gl.RGBA; - case Format.R11G11B10F: return gl.RGB; - case Format.R5G6B5: return gl.RGB; - case Format.RGB5A1: return gl.RGBA; - case Format.RGBA4: return gl.RGBA; - case Format.D16: return gl.DEPTH_COMPONENT; - case Format.D16S8: return gl.DEPTH_STENCIL; - case Format.D24: return gl.DEPTH_COMPONENT; - case Format.D24S8: return gl.DEPTH_STENCIL; - case Format.D32F: return gl.DEPTH_COMPONENT; - case Format.D32F_S8: return gl.DEPTH_STENCIL; + case Format.A8: return gl.ALPHA; + case Format.L8: return gl.LUMINANCE; + case Format.LA8: return gl.LUMINANCE_ALPHA; + case Format.R8: + case Format.R8SN: return gl.RED; + case Format.R8UI: + case Format.R8I: return gl.RED; + case Format.RG8: + case Format.RG8SN: + case Format.RG8UI: + case Format.RG8I: return gl.RG; + case Format.RGB8: + case Format.RGB8SN: + case Format.RGB8UI: + case Format.RGB8I: return gl.RGB; + case Format.BGRA8: + case Format.RGBA8: + case Format.RGBA8SN: + case Format.RGBA8UI: + case Format.RGBA8I: return gl.RGBA; + case Format.R16UI: + case Format.R16I: + case Format.R16F: return gl.RED; + case Format.RG16UI: + case Format.RG16I: + case Format.RG16F: return gl.RG; + case Format.RGB16UI: + case Format.RGB16I: + case Format.RGB16F: return gl.RGB; + case Format.RGBA16UI: + case Format.RGBA16I: + case Format.RGBA16F: return gl.RGBA; + case Format.R32UI: + case Format.R32I: + case Format.R32F: return gl.RED; + case Format.RG32UI: + case Format.RG32I: + case Format.RG32F: return gl.RG; + case Format.RGB32UI: + case Format.RGB32I: + case Format.RGB32F: return gl.RGB; + case Format.RGBA32UI: + case Format.RGBA32I: + case Format.RGBA32F: return gl.RGBA; + case Format.RGB10A2: return gl.RGBA; + case Format.R11G11B10F: return gl.RGB; + case Format.R5G6B5: return gl.RGB; + case Format.RGB5A1: return gl.RGBA; + case Format.RGBA4: return gl.RGBA; + case Format.D16: return gl.DEPTH_COMPONENT; + case Format.D16S8: return gl.DEPTH_STENCIL; + case Format.D24: return gl.DEPTH_COMPONENT; + case Format.D24S8: return gl.DEPTH_STENCIL; + case Format.D32F: return gl.DEPTH_COMPONENT; + case Format.D32F_S8: return gl.DEPTH_STENCIL; - case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; - case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; - case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; - case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; - case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; - case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + case Format.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case Format.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case Format.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case Format.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case Format.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case Format.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case Format.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case Format.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; - case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; - case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; - case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; - case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; - case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; - case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; - case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; - case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; - case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; + case Format.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + case Format.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; + case Format.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; + case Format.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case Format.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; + case Format.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + case Format.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; + case Format.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; + case Format.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; + case Format.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; - case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case Format.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case Format.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; - case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; - case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; - case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; - case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; - case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; - case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; - case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; - case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; - case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; - case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; - case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; - case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; - case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; + case Format.ASTC_RGBA_4x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR; + case Format.ASTC_RGBA_5x4: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR; + case Format.ASTC_RGBA_5x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR; + case Format.ASTC_RGBA_6x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR; + case Format.ASTC_RGBA_6x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR; + case Format.ASTC_RGBA_8x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR; + case Format.ASTC_RGBA_8x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR; + case Format.ASTC_RGBA_8x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR; + case Format.ASTC_RGBA_10x5: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR; + case Format.ASTC_RGBA_10x6: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR; + case Format.ASTC_RGBA_10x8: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR; + case Format.ASTC_RGBA_10x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR; + case Format.ASTC_RGBA_12x10: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR; + case Format.ASTC_RGBA_12x12: return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR; - case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; - case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; - case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; - case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; - case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; - case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; - case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; - case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; - case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; - case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; - case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; - case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; - case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; - case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; + case Format.ASTC_SRGBA_4x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; + case Format.ASTC_SRGBA_5x4: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; + case Format.ASTC_SRGBA_5x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; + case Format.ASTC_SRGBA_6x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; + case Format.ASTC_SRGBA_6x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; + case Format.ASTC_SRGBA_8x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; + case Format.ASTC_SRGBA_8x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; + case Format.ASTC_SRGBA_8x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; + case Format.ASTC_SRGBA_10x5: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; + case Format.ASTC_SRGBA_10x6: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; + case Format.ASTC_SRGBA_10x8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; + case Format.ASTC_SRGBA_10x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; + case Format.ASTC_SRGBA_12x10: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; + case Format.ASTC_SRGBA_12x12: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; - default: { - console.error('Unsupported Format, convert to WebGL format failed.'); - return gl.RGBA; - } + default: { + console.error('Unsupported Format, convert to WebGL format failed.'); + return gl.RGBA; + } } } function GFXTypeToWebGLType (type: Type, gl: WebGL2RenderingContext): GLenum { switch (type) { - case Type.BOOL: return gl.BOOL; - case Type.BOOL2: return gl.BOOL_VEC2; - case Type.BOOL3: return gl.BOOL_VEC3; - case Type.BOOL4: return gl.BOOL_VEC4; - case Type.INT: return gl.INT; - case Type.INT2: return gl.INT_VEC2; - case Type.INT3: return gl.INT_VEC3; - case Type.INT4: return gl.INT_VEC4; - case Type.UINT: return gl.UNSIGNED_INT; - case Type.FLOAT: return gl.FLOAT; - case Type.FLOAT2: return gl.FLOAT_VEC2; - case Type.FLOAT3: return gl.FLOAT_VEC3; - case Type.FLOAT4: return gl.FLOAT_VEC4; - case Type.MAT2: return gl.FLOAT_MAT2; - case Type.MAT2X3: return gl.FLOAT_MAT2x3; - case Type.MAT2X4: return gl.FLOAT_MAT2x4; - case Type.MAT3X2: return gl.FLOAT_MAT3x2; - case Type.MAT3: return gl.FLOAT_MAT3; - case Type.MAT3X4: return gl.FLOAT_MAT3x4; - case Type.MAT4X2: return gl.FLOAT_MAT4x2; - case Type.MAT4X3: return gl.FLOAT_MAT4x3; - case Type.MAT4: return gl.FLOAT_MAT4; - case Type.SAMPLER2D: return gl.SAMPLER_2D; - case Type.SAMPLER2D_ARRAY: return gl.SAMPLER_2D_ARRAY; - case Type.SAMPLER3D: return gl.SAMPLER_3D; - case Type.SAMPLER_CUBE: return gl.SAMPLER_CUBE; - default: { - console.error('Unsupported GLType, convert to GL type failed.'); - return Type.UNKNOWN; - } + case Type.BOOL: return gl.BOOL; + case Type.BOOL2: return gl.BOOL_VEC2; + case Type.BOOL3: return gl.BOOL_VEC3; + case Type.BOOL4: return gl.BOOL_VEC4; + case Type.INT: return gl.INT; + case Type.INT2: return gl.INT_VEC2; + case Type.INT3: return gl.INT_VEC3; + case Type.INT4: return gl.INT_VEC4; + case Type.UINT: return gl.UNSIGNED_INT; + case Type.FLOAT: return gl.FLOAT; + case Type.FLOAT2: return gl.FLOAT_VEC2; + case Type.FLOAT3: return gl.FLOAT_VEC3; + case Type.FLOAT4: return gl.FLOAT_VEC4; + case Type.MAT2: return gl.FLOAT_MAT2; + case Type.MAT2X3: return gl.FLOAT_MAT2x3; + case Type.MAT2X4: return gl.FLOAT_MAT2x4; + case Type.MAT3X2: return gl.FLOAT_MAT3x2; + case Type.MAT3: return gl.FLOAT_MAT3; + case Type.MAT3X4: return gl.FLOAT_MAT3x4; + case Type.MAT4X2: return gl.FLOAT_MAT4x2; + case Type.MAT4X3: return gl.FLOAT_MAT4x3; + case Type.MAT4: return gl.FLOAT_MAT4; + case Type.SAMPLER2D: return gl.SAMPLER_2D; + case Type.SAMPLER2D_ARRAY: return gl.SAMPLER_2D_ARRAY; + case Type.SAMPLER3D: return gl.SAMPLER_3D; + case Type.SAMPLER_CUBE: return gl.SAMPLER_CUBE; + default: { + console.error('Unsupported GLType, convert to GL type failed.'); + return Type.UNKNOWN; + } } } function WebGLTypeToGFXType (glType: GLenum, gl: WebGL2RenderingContext): Type { switch (glType) { - case gl.BOOL: return Type.BOOL; - case gl.BOOL_VEC2: return Type.BOOL2; - case gl.BOOL_VEC3: return Type.BOOL3; - case gl.BOOL_VEC4: return Type.BOOL4; - case gl.INT: return Type.INT; - case gl.INT_VEC2: return Type.INT2; - case gl.INT_VEC3: return Type.INT3; - case gl.INT_VEC4: return Type.INT4; - case gl.UNSIGNED_INT: return Type.UINT; - case gl.UNSIGNED_INT_VEC2: return Type.UINT2; - case gl.UNSIGNED_INT_VEC3: return Type.UINT3; - case gl.UNSIGNED_INT_VEC4: return Type.UINT4; - case gl.UNSIGNED_INT: return Type.UINT; - case gl.FLOAT: return Type.FLOAT; - case gl.FLOAT_VEC2: return Type.FLOAT2; - case gl.FLOAT_VEC3: return Type.FLOAT3; - case gl.FLOAT_VEC4: return Type.FLOAT4; - case gl.FLOAT_MAT2: return Type.MAT2; - case gl.FLOAT_MAT2x3: return Type.MAT2X3; - case gl.FLOAT_MAT2x4: return Type.MAT2X4; - case gl.FLOAT_MAT3x2: return Type.MAT3X2; - case gl.FLOAT_MAT3: return Type.MAT3; - case gl.FLOAT_MAT3x4: return Type.MAT3X4; - case gl.FLOAT_MAT4x2: return Type.MAT4X2; - case gl.FLOAT_MAT4x3: return Type.MAT4X3; - case gl.FLOAT_MAT4: return Type.MAT4; - case gl.SAMPLER_2D: return Type.SAMPLER2D; - case gl.SAMPLER_2D_ARRAY: return Type.SAMPLER2D_ARRAY; - case gl.SAMPLER_3D: return Type.SAMPLER3D; - case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; - default: { - console.error('Unsupported GLType, convert to Type failed.'); - return Type.UNKNOWN; - } + case gl.BOOL: return Type.BOOL; + case gl.BOOL_VEC2: return Type.BOOL2; + case gl.BOOL_VEC3: return Type.BOOL3; + case gl.BOOL_VEC4: return Type.BOOL4; + case gl.INT: return Type.INT; + case gl.INT_VEC2: return Type.INT2; + case gl.INT_VEC3: return Type.INT3; + case gl.INT_VEC4: return Type.INT4; + case gl.UNSIGNED_INT: return Type.UINT; + case gl.UNSIGNED_INT_VEC2: return Type.UINT2; + case gl.UNSIGNED_INT_VEC3: return Type.UINT3; + case gl.UNSIGNED_INT_VEC4: return Type.UINT4; + case gl.FLOAT: return Type.FLOAT; + case gl.FLOAT_VEC2: return Type.FLOAT2; + case gl.FLOAT_VEC3: return Type.FLOAT3; + case gl.FLOAT_VEC4: return Type.FLOAT4; + case gl.FLOAT_MAT2: return Type.MAT2; + case gl.FLOAT_MAT2x3: return Type.MAT2X3; + case gl.FLOAT_MAT2x4: return Type.MAT2X4; + case gl.FLOAT_MAT3x2: return Type.MAT3X2; + case gl.FLOAT_MAT3: return Type.MAT3; + case gl.FLOAT_MAT3x4: return Type.MAT3X4; + case gl.FLOAT_MAT4x2: return Type.MAT4X2; + case gl.FLOAT_MAT4x3: return Type.MAT4X3; + case gl.FLOAT_MAT4: return Type.MAT4; + case gl.SAMPLER_2D: return Type.SAMPLER2D; + case gl.SAMPLER_2D_ARRAY: return Type.SAMPLER2D_ARRAY; + case gl.SAMPLER_3D: return Type.SAMPLER3D; + case gl.SAMPLER_CUBE: return Type.SAMPLER_CUBE; + default: { + console.error('Unsupported GLType, convert to Type failed.'); + return Type.UNKNOWN; + } } } function WebGLGetTypeSize (glType: GLenum, gl: WebGL2RenderingContext): Type { switch (glType) { - case gl.BOOL: return 4; - case gl.BOOL_VEC2: return 8; - case gl.BOOL_VEC3: return 12; - case gl.BOOL_VEC4: return 16; - case gl.INT: return 4; - case gl.INT_VEC2: return 8; - case gl.INT_VEC3: return 12; - case gl.INT_VEC4: return 16; - case gl.UNSIGNED_INT: return 4; - case gl.UNSIGNED_INT_VEC2: return 8; - case gl.UNSIGNED_INT_VEC3: return 12; - case gl.UNSIGNED_INT_VEC4: return 16; - case gl.FLOAT: return 4; - case gl.FLOAT_VEC2: return 8; - case gl.FLOAT_VEC3: return 12; - case gl.FLOAT_VEC4: return 16; - case gl.FLOAT_MAT2: return 16; - case gl.FLOAT_MAT2x3: return 24; - case gl.FLOAT_MAT2x4: return 32; - case gl.FLOAT_MAT3x2: return 24; - case gl.FLOAT_MAT3: return 36; - case gl.FLOAT_MAT3x4: return 48; - case gl.FLOAT_MAT4x2: return 32; - case gl.FLOAT_MAT4x3: return 48; - case gl.FLOAT_MAT4: return 64; - case gl.SAMPLER_2D: return 4; - case gl.SAMPLER_2D_ARRAY: return 4; - case gl.SAMPLER_2D_ARRAY_SHADOW: return 4; - case gl.SAMPLER_3D: return 4; - case gl.SAMPLER_CUBE: return 4; - case gl.INT_SAMPLER_2D: return 4; - case gl.INT_SAMPLER_2D_ARRAY: return 4; - case gl.INT_SAMPLER_3D: return 4; - case gl.INT_SAMPLER_CUBE: return 4; - case gl.UNSIGNED_INT_SAMPLER_2D: return 4; - case gl.UNSIGNED_INT_SAMPLER_2D_ARRAY: return 4; - case gl.UNSIGNED_INT_SAMPLER_3D: return 4; - case gl.UNSIGNED_INT_SAMPLER_CUBE: return 4; - default: { - console.error('Unsupported GLType, get type failed.'); - return 0; - } + case gl.BOOL: return 4; + case gl.BOOL_VEC2: return 8; + case gl.BOOL_VEC3: return 12; + case gl.BOOL_VEC4: return 16; + case gl.INT: return 4; + case gl.INT_VEC2: return 8; + case gl.INT_VEC3: return 12; + case gl.INT_VEC4: return 16; + case gl.UNSIGNED_INT: return 4; + case gl.UNSIGNED_INT_VEC2: return 8; + case gl.UNSIGNED_INT_VEC3: return 12; + case gl.UNSIGNED_INT_VEC4: return 16; + case gl.FLOAT: return 4; + case gl.FLOAT_VEC2: return 8; + case gl.FLOAT_VEC3: return 12; + case gl.FLOAT_VEC4: return 16; + case gl.FLOAT_MAT2: return 16; + case gl.FLOAT_MAT2x3: return 24; + case gl.FLOAT_MAT2x4: return 32; + case gl.FLOAT_MAT3x2: return 24; + case gl.FLOAT_MAT3: return 36; + case gl.FLOAT_MAT3x4: return 48; + case gl.FLOAT_MAT4x2: return 32; + case gl.FLOAT_MAT4x3: return 48; + case gl.FLOAT_MAT4: return 64; + case gl.SAMPLER_2D: return 4; + case gl.SAMPLER_2D_ARRAY: return 4; + case gl.SAMPLER_2D_ARRAY_SHADOW: return 4; + case gl.SAMPLER_3D: return 4; + case gl.SAMPLER_CUBE: return 4; + case gl.INT_SAMPLER_2D: return 4; + case gl.INT_SAMPLER_2D_ARRAY: return 4; + case gl.INT_SAMPLER_3D: return 4; + case gl.INT_SAMPLER_CUBE: return 4; + case gl.UNSIGNED_INT_SAMPLER_2D: return 4; + case gl.UNSIGNED_INT_SAMPLER_2D_ARRAY: return 4; + case gl.UNSIGNED_INT_SAMPLER_3D: return 4; + case gl.UNSIGNED_INT_SAMPLER_CUBE: return 4; + default: { + console.error('Unsupported GLType, get type failed.'); + return 0; + } } } function WebGLGetComponentCount (glType: GLenum, gl: WebGL2RenderingContext): Type { switch (glType) { - case gl.FLOAT_MAT2: return 2; - case gl.FLOAT_MAT2x3: return 2; - case gl.FLOAT_MAT2x4: return 2; - case gl.FLOAT_MAT3x2: return 3; - case gl.FLOAT_MAT3: return 3; - case gl.FLOAT_MAT3x4: return 3; - case gl.FLOAT_MAT4x2: return 4; - case gl.FLOAT_MAT4x3: return 4; - case gl.FLOAT_MAT4: return 4; - default: { - return 1; - } + case gl.FLOAT_MAT2: return 2; + case gl.FLOAT_MAT2x3: return 2; + case gl.FLOAT_MAT2x4: return 2; + case gl.FLOAT_MAT3x2: return 3; + case gl.FLOAT_MAT3: return 3; + case gl.FLOAT_MAT3x4: return 3; + case gl.FLOAT_MAT4x2: return 4; + case gl.FLOAT_MAT4x3: return 4; + case gl.FLOAT_MAT4: return 4; + default: { + return 1; + } } } @@ -649,7 +646,8 @@ export enum WebGL2Cmd { export abstract class WebGL2CmdObject { public cmdType: WebGL2Cmd; - public refCount: number = 0; + + public refCount = 0; constructor (type: WebGL2Cmd) { this.cmdType = type; @@ -659,13 +657,17 @@ export abstract class WebGL2CmdObject { } export class WebGL2CmdBeginRenderPass extends WebGL2CmdObject { - public gpuRenderPass: IWebGL2GPURenderPass | null = null; + public gpuFramebuffer: IWebGL2GPUFramebuffer | null = null; + public renderArea = new Rect(); + public clearColors: Color[] = []; - public clearDepth: number = 1.0; - public clearStencil: number = 0; + + public clearDepth = 1.0; + + public clearStencil = 0; constructor () { super(WebGL2Cmd.BEGIN_RENDER_PASS); @@ -678,18 +680,28 @@ export class WebGL2CmdBeginRenderPass extends WebGL2CmdObject { } export class WebGL2CmdBindStates extends WebGL2CmdObject { - public gpuPipelineState: IWebGL2GPUPipelineState | null = null; + public gpuInputAssembler: IWebGL2GPUInputAssembler | null = null; + public gpuDescriptorSets: IWebGL2GPUDescriptorSet[] = []; + public dynamicOffsets: number[] = []; + public viewport: Viewport | null = null; + public scissor: Rect | null = null; + public lineWidth: number | null = null; + public depthBias: IWebGL2DepthBias | null = null; + public blendConstants: number[] = []; + public depthBounds: IWebGL2DepthBounds | null = null; + public stencilWriteMask: IWebGL2StencilWriteMask | null = null; + public stencilCompareMask: IWebGL2StencilCompareMask | null = null; constructor () { @@ -713,7 +725,6 @@ export class WebGL2CmdBindStates extends WebGL2CmdObject { } export class WebGL2CmdDraw extends WebGL2CmdObject { - public drawInfo = new DrawInfo(); constructor () { @@ -725,11 +736,13 @@ export class WebGL2CmdDraw extends WebGL2CmdObject { } export class WebGL2CmdUpdateBuffer extends WebGL2CmdObject { - public gpuBuffer: IWebGL2GPUBuffer | null = null; + public buffer: BufferSource | null = null; - public offset: number = 0; - public size: number = 0; + + public offset = 0; + + public size = 0; constructor () { super(WebGL2Cmd.UPDATE_BUFFER); @@ -742,9 +755,10 @@ export class WebGL2CmdUpdateBuffer extends WebGL2CmdObject { } export class WebGL2CmdCopyBufferToTexture extends WebGL2CmdObject { - public gpuTexture: IWebGL2GPUTexture | null = null; + public buffers: ArrayBufferView[] = []; + public regions: BufferTextureCopy[] = []; constructor () { @@ -760,14 +774,18 @@ export class WebGL2CmdCopyBufferToTexture extends WebGL2CmdObject { export class WebGL2CmdPackage { public cmds: CachedArray = new CachedArray(1); + public beginRenderPassCmds: CachedArray = new CachedArray(1); + public bindStatesCmds: CachedArray = new CachedArray(1); + public drawCmds: CachedArray = new CachedArray(1); + public updateBufferCmds: CachedArray = new CachedArray(1); + public copyBufferToTextureCmds: CachedArray = new CachedArray(1); public clearCmds (allocator: WebGL2CommandAllocator) { - if (this.beginRenderPassCmds.length) { allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds); this.beginRenderPassCmds.clear(); @@ -798,13 +816,11 @@ export class WebGL2CmdPackage { } export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer) { - - const gl = device.gl; + const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; if (gpuBuffer.usage & BufferUsageBit.VERTEX) { - gpuBuffer.glTarget = gl.ARRAY_BUFFER; const glBuffer = gl.createBuffer(); @@ -830,7 +846,6 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWeb } } } else if (gpuBuffer.usage & BufferUsageBit.INDEX) { - gpuBuffer.glTarget = gl.ELEMENT_ARRAY_BUFFER; const glBuffer = gl.createBuffer(); if (glBuffer) { @@ -855,7 +870,6 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWeb } } } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) { - gpuBuffer.glTarget = gl.UNIFORM_BUFFER; const glBuffer = gl.createBuffer(); if (glBuffer && gpuBuffer.size > 0) { @@ -883,31 +897,32 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2Device, gpuBuffer: IWeb } export function WebGL2CmdFuncDestroyBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer) { - const gl = device.gl; + const { gl } = device; if (gpuBuffer.glBuffer) { // Firefox 75+ implicitly unbind whatever buffer there was on the slot sometimes // can be reproduced in the static batching scene at https://github.com/cocos-creator/test-cases-3d switch (gpuBuffer.glTarget) { - case gl.ARRAY_BUFFER: - if (device.useVAO && device.stateCache.glVAO) { - gl.bindVertexArray(null); - device.stateCache.glVAO = gfxStateCache.gpuInputAssembler = null; - } - gl.bindBuffer(gl.ARRAY_BUFFER, null); - device.stateCache.glArrayBuffer = null; - break; - case gl.ELEMENT_ARRAY_BUFFER: - if (device.useVAO && device.stateCache.glVAO) { - gl.bindVertexArray(null); - device.stateCache.glVAO = gfxStateCache.gpuInputAssembler = null; - } - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); - device.stateCache.glElementArrayBuffer = null; - break; - case gl.UNIFORM_BUFFER: - gl.bindBuffer(gl.UNIFORM_BUFFER, null); - device.stateCache.glUniformBuffer = null; - break; + case gl.ARRAY_BUFFER: + if (device.useVAO && device.stateCache.glVAO) { + gl.bindVertexArray(null); + device.stateCache.glVAO = gfxStateCache.gpuInputAssembler = null; + } + gl.bindBuffer(gl.ARRAY_BUFFER, null); + device.stateCache.glArrayBuffer = null; + break; + case gl.ELEMENT_ARRAY_BUFFER: + if (device.useVAO && device.stateCache.glVAO) { + gl.bindVertexArray(null); + device.stateCache.glVAO = gfxStateCache.gpuInputAssembler = null; + } + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); + device.stateCache.glElementArrayBuffer = null; + break; + case gl.UNIFORM_BUFFER: + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + device.stateCache.glUniformBuffer = null; + break; + default: } gl.deleteBuffer(gpuBuffer.glBuffer); @@ -916,8 +931,7 @@ export function WebGL2CmdFuncDestroyBuffer (device: WebGL2Device, gpuBuffer: IWe } export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer) { - - const gl = device.gl; + const { gl } = device; const cache = device.stateCache; const glUsage: GLenum = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW; @@ -967,9 +981,9 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb gl.bufferData(gl.UNIFORM_BUFFER, gpuBuffer.size, glUsage); gl.bindBuffer(gl.UNIFORM_BUFFER, null); device.stateCache.glUniformBuffer = null; - } else if ((gpuBuffer.usage & BufferUsageBit.INDIRECT) || - (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) || - (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { + } else if ((gpuBuffer.usage & BufferUsageBit.INDIRECT) + || (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) + || (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC)) { gpuBuffer.glTarget = gl.NONE; } else { console.error('Unsupported BufferType, create buffer failed.'); @@ -978,76 +992,73 @@ export function WebGL2CmdFuncResizeBuffer (device: WebGL2Device, gpuBuffer: IWeb } export function WebGL2CmdFuncUpdateBuffer (device: WebGL2Device, gpuBuffer: IWebGL2GPUBuffer, buffer: BufferSource, offset: number, size: number) { - if (gpuBuffer.usage & BufferUsageBit.INDIRECT) { gpuBuffer.indirects.length = offset; Array.prototype.push.apply(gpuBuffer.indirects, (buffer as IndirectBuffer).drawInfos); } else { const buff = buffer as ArrayBuffer; - const gl = device.gl; + const { gl } = device; const cache = device.stateCache; switch (gpuBuffer.glTarget) { - case gl.ARRAY_BUFFER: { - if (cache.glVAO) { - gl.bindVertexArray(null); - cache.glVAO = gfxStateCache.gpuInputAssembler = null; - } - - if (cache.glArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer); - cache.glArrayBuffer = gpuBuffer.glBuffer; - } - - if (size === buff.byteLength) { - gl.bufferSubData(gpuBuffer.glTarget, offset, buff); - } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); - } - break; + case gl.ARRAY_BUFFER: { + if (cache.glVAO) { + gl.bindVertexArray(null); + cache.glVAO = gfxStateCache.gpuInputAssembler = null; } - case gl.ELEMENT_ARRAY_BUFFER: { - if (cache.glVAO) { - gl.bindVertexArray(null); - cache.glVAO = gfxStateCache.gpuInputAssembler = null; - } - if (cache.glElementArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); - cache.glElementArrayBuffer = gpuBuffer.glBuffer; - } + if (cache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer); + cache.glArrayBuffer = gpuBuffer.glBuffer; + } - if (size === buff.byteLength) { - gl.bufferSubData(gpuBuffer.glTarget, offset, buff); - } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); - } - break; + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); + } else { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); + } + break; + } + case gl.ELEMENT_ARRAY_BUFFER: { + if (cache.glVAO) { + gl.bindVertexArray(null); + cache.glVAO = gfxStateCache.gpuInputAssembler = null; } - case gl.UNIFORM_BUFFER: { - if (cache.glUniformBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer); - cache.glUniformBuffer = gpuBuffer.glBuffer; - } - if (size === buff.byteLength) { - gl.bufferSubData(gpuBuffer.glTarget, offset, buff); - } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buff, 0, size / 4)); - } - break; + if (cache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + cache.glElementArrayBuffer = gpuBuffer.glBuffer; } - default: { - console.error('Unsupported BufferType, update buffer failed.'); - return; + + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); + } else { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); } + break; + } + case gl.UNIFORM_BUFFER: { + if (cache.glUniformBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer); + cache.glUniformBuffer = gpuBuffer.glBuffer; + } + + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); + } else { + gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buff, 0, size / 4)); + } + break; + } + default: { + console.error('Unsupported BufferType, update buffer failed.'); + } } } } export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture) { - - const gl = device.gl; + const { gl } = device; gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl); @@ -1057,49 +1068,46 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW let h = gpuTexture.height; switch (gpuTexture.type) { - case TextureType.TEX2D: { - gpuTexture.glTarget = gl.TEXTURE_2D; + case TextureType.TEX2D: { + gpuTexture.glTarget = gl.TEXTURE_2D; - const maxSize = Math.max(w, h); - if (maxSize > device.maxTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); - } + const maxSize = Math.max(w, h); + if (maxSize > device.maxTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); + } - if (gpuTexture.samples === SampleCount.X1) { - const glTexture = gl.createTexture(); - if (glTexture && gpuTexture.size > 0) { - gpuTexture.glTexture = glTexture; - const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; + if (gpuTexture.samples === SampleCount.X1) { + const glTexture = gl.createTexture(); + if (glTexture && gpuTexture.size > 0) { + gpuTexture.glTexture = glTexture; + const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; - if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); - glTexUnit.glTexture = gpuTexture.glTexture; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + if (!FormatInfos[gpuTexture.format].isCompressed) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); } - - if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } - else { - // init 2 x 2 texture - const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_2D, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); - } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); } - /* + } else { + // init 2 x 2 texture + const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_2D, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); + } + /* if (gpuTexture.isPowerOf2) { gpuTexture.glWrapS = gl.REPEAT; gpuTexture.glWrapT = gl.REPEAT; @@ -1114,76 +1122,74 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); */ + } else { + gl.deleteTexture(glTexture); + } + } else { + const glRenderbuffer = gl.createRenderbuffer(); + if (glRenderbuffer && gpuTexture.size > 0) { + gpuTexture.glRenderbuffer = glRenderbuffer; + if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); + device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; } - else { - gl.deleteTexture(glTexture); + + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, SAMPLES[gpuTexture.samples], + gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); + } + } + break; + } + case TextureType.CUBE: { + gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; + + const maxSize = Math.max(w, h); + if (maxSize > device.maxCubeMapTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); + } + + const glTexture = gl.createTexture(); + if (glTexture && gpuTexture.size > 0) { + gpuTexture.glTexture = glTexture; + const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + if (!FormatInfos[gpuTexture.format].isCompressed) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, + gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } } } else { - const glRenderbuffer = gl.createRenderbuffer(); - if (glRenderbuffer && gpuTexture.size > 0) { - gpuTexture.glRenderbuffer = glRenderbuffer; - if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { - gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); - device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; - } - - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, SAMPLES[gpuTexture.samples], gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); + for (let f = 0; f < 6; ++f) { + const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); } } - break; - } - case TextureType.CUBE: { - gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; - const maxSize = Math.max(w, h); - if (maxSize > device.maxCubeMapTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); - } - - const glTexture = gl.createTexture(); - if (glTexture && gpuTexture.size > 0) { - gpuTexture.glTexture = glTexture; - const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; - - if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); - glTexUnit.glTexture = gpuTexture.glTexture; - } - - if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } - } - else { - for (let f = 0; f < 6; ++f) { - const imgSize = FormatSize(gpuTexture.format, 2, 2, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, 0, gpuTexture.glInternalFmt, 2, 2, 0, view); - } - } - } - - /* + /* if (gpuTexture.isPowerOf2) { gpuTexture.glWrapS = gl.REPEAT; gpuTexture.glWrapT = gl.REPEAT; @@ -1199,14 +1205,14 @@ export function WebGL2CmdFuncCreateTexture (device: WebGL2Device, gpuTexture: IW gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter); gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter); */ - } - break; - } - default: { - console.error('Unsupported TextureType, create texture failed.'); - gpuTexture.type = TextureType.TEX2D; - gpuTexture.glTarget = gl.TEXTURE_2D; } + break; + } + default: { + console.error('Unsupported TextureType, create texture failed.'); + gpuTexture.type = TextureType.TEX2D; + gpuTexture.glTarget = gl.TEXTURE_2D; + } } } @@ -1223,8 +1229,7 @@ export function WebGL2CmdFuncDestroyTexture (device: WebGL2Device, gpuTexture: I } export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IWebGL2GPUTexture) { - - const gl = device.gl; + const { gl } = device; gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl); @@ -1234,107 +1239,104 @@ export function WebGL2CmdFuncResizeTexture (device: WebGL2Device, gpuTexture: IW let h = gpuTexture.height; switch (gpuTexture.type) { - case TextureType.TEX2D: { - gpuTexture.glTarget = gl.TEXTURE_2D; + case TextureType.TEX2D: { + gpuTexture.glTarget = gl.TEXTURE_2D; - const maxSize = Math.max(w, h); - if (maxSize > device.maxTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); - } - - if (gpuTexture.samples === SampleCount.X1) { - const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; - - if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); - glTexUnit.glTexture = gpuTexture.glTexture; - } - - if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } - } - } else { - const glRenderbuffer = gl.createRenderbuffer(); - if (glRenderbuffer && gpuTexture.size > 0) { - gpuTexture.glRenderbuffer = glRenderbuffer; - if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { - gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); - device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; - } - - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, SAMPLES[gpuTexture.samples], gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); - } - } - break; + const maxSize = Math.max(w, h); + if (maxSize > device.maxTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); } - case TextureType.CUBE: { - gpuTexture.type = TextureType.CUBE; - gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; - - const maxSize = Math.max(w, h); - if (maxSize > device.maxCubeMapTextureSize) { - errorID(9100, maxSize, device.maxTextureSize); - } + if (gpuTexture.samples === SampleCount.X1) { const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture); glTexUnit.glTexture = gpuTexture.glTexture; } if (!FormatInfos[gpuTexture.format].isCompressed) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); } - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - for (let f = 0; f < 6; ++f) { - w = gpuTexture.width; - h = gpuTexture.height; - for (let i = 0; i < gpuTexture.mipLevel; ++i) { - const imgSize = FormatSize(gpuTexture.format, w, h, 1); - const view: Uint8Array = new Uint8Array(imgSize); - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); - w = Math.max(1, w >> 1); - h = Math.max(1, h >> 1); - } - } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); } } - break; + } else { + const glRenderbuffer = gl.createRenderbuffer(); + if (glRenderbuffer && gpuTexture.size > 0) { + gpuTexture.glRenderbuffer = glRenderbuffer; + if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer); + device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer; + } + + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, SAMPLES[gpuTexture.samples], + gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height); + } } - default: { - console.error('Unsupported TextureType, create texture failed.'); - gpuTexture.type = TextureType.TEX2D; - gpuTexture.glTarget = gl.TEXTURE_2D; + break; + } + case TextureType.CUBE: { + gpuTexture.type = TextureType.CUBE; + gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP; + + const maxSize = Math.max(w, h); + if (maxSize > device.maxCubeMapTextureSize) { + errorID(9100, maxSize, device.maxTextureSize); } + + const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + if (!FormatInfos[gpuTexture.format].isCompressed) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, + 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + for (let f = 0; f < 6; ++f) { + w = gpuTexture.width; + h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + const imgSize = FormatSize(gpuTexture.format, w, h, 1); + const view: Uint8Array = new Uint8Array(imgSize); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternalFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } + break; + } + default: { + console.error('Unsupported TextureType, create texture failed.'); + gpuTexture.type = TextureType.TEX2D; + gpuTexture.glTarget = gl.TEXTURE_2D; + } } } export function WebGL2CmdFuncCreateSampler (device: WebGL2Device, gpuSampler: IWebGL2GPUSampler) { - - const gl = device.gl; + const { gl } = device; const glSampler = gl.createSampler(); if (glSampler) { if (gpuSampler.minFilter === Filter.LINEAR || gpuSampler.minFilter === Filter.ANISOTROPIC) { @@ -1345,14 +1347,12 @@ export function WebGL2CmdFuncCreateSampler (device: WebGL2Device, gpuSampler: IW } else { gpuSampler.glMinFilter = gl.LINEAR; } + } else if (gpuSampler.mipFilter === Filter.LINEAR || gpuSampler.mipFilter === Filter.ANISOTROPIC) { + gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_LINEAR; + } else if (gpuSampler.mipFilter === Filter.POINT) { + gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_NEAREST; } else { - if (gpuSampler.mipFilter === Filter.LINEAR || gpuSampler.mipFilter === Filter.ANISOTROPIC) { - gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_LINEAR; - } else if (gpuSampler.mipFilter === Filter.POINT) { - gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_NEAREST; - } else { - gpuSampler.glMinFilter = gl.NEAREST; - } + gpuSampler.glMinFilter = gl.NEAREST; } if (gpuSampler.magFilter === Filter.LINEAR || gpuSampler.magFilter === Filter.ANISOTROPIC) { @@ -1386,7 +1386,7 @@ export function WebGL2CmdFuncDestroySampler (device: WebGL2Device, gpuSampler: I export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebuffer: IWebGL2GPUFramebuffer) { if (!gpuFramebuffer.gpuColorTextures.length && !gpuFramebuffer.gpuDepthStencilTexture) { return; } // onscreen fbo - const gl = device.gl; + const { gl } = device; const attachments: GLenum[] = []; const glFramebuffer = gl.createFramebuffer(); @@ -1398,7 +1398,6 @@ export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebu } for (let i = 0; i < gpuFramebuffer.gpuColorTextures.length; ++i) { - const colorTexture = gpuFramebuffer.gpuColorTextures[i]; if (colorTexture) { if (colorTexture.glTexture) { @@ -1407,7 +1406,8 @@ export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebu gl.COLOR_ATTACHMENT0 + i, colorTexture.glTarget, colorTexture.glTexture, - 0); // level should be 0. + 0, + ); // level should be 0. } else { gl.framebufferRenderbuffer( gl.FRAMEBUFFER, @@ -1430,7 +1430,8 @@ export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebu glAttachment, dst.glTarget, dst.glTexture, - 0); // level must be 0 + 0, + ); // level must be 0 } else { gl.framebufferRenderbuffer( gl.FRAMEBUFFER, @@ -1446,23 +1447,23 @@ export function WebGL2CmdFuncCreateFramebuffer (device: WebGL2Device, gpuFramebu const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status !== gl.FRAMEBUFFER_COMPLETE) { switch (status) { - case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); - break; - } - case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); - break; - } - case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); - break; - } - case gl.FRAMEBUFFER_UNSUPPORTED: { - console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); - break; - } - default: + case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); + break; + } + case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); + break; + } + case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); + break; + } + case gl.FRAMEBUFFER_UNSUPPORTED: { + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); + break; + } + default: } } @@ -1480,7 +1481,7 @@ export function WebGL2CmdFuncDestroyFramebuffer (device: WebGL2Device, gpuFrameb } export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWebGL2GPUShader) { - const gl = device.gl; + const { gl } = device; for (let k = 0; k < gpuShader.gpuStages.length; k++) { const gpuStage = gpuShader.gpuStages[k]; @@ -1490,30 +1491,30 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb let lineNumber = 1; switch (gpuStage.type) { - case ShaderStageFlagBit.VERTEX: { - shaderTypeStr = 'VertexShader'; - glShaderType = gl.VERTEX_SHADER; - break; - } - case ShaderStageFlagBit.FRAGMENT: { - shaderTypeStr = 'FragmentShader'; - glShaderType = gl.FRAGMENT_SHADER; - break; - } - default: { - console.error('Unsupported ShaderType.'); - return; - } + case ShaderStageFlagBit.VERTEX: { + shaderTypeStr = 'VertexShader'; + glShaderType = gl.VERTEX_SHADER; + break; + } + case ShaderStageFlagBit.FRAGMENT: { + shaderTypeStr = 'FragmentShader'; + glShaderType = gl.FRAGMENT_SHADER; + break; + } + default: { + console.error('Unsupported ShaderType.'); + return; + } } const glShader = gl.createShader(glShaderType); if (glShader) { gpuStage.glShader = glShader; - gl.shaderSource(gpuStage.glShader, '#version 300 es\n' + gpuStage.source); + gl.shaderSource(gpuStage.glShader, `#version 300 es\n${gpuStage.source}`); gl.compileShader(gpuStage.glShader); if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { - console.error(shaderTypeStr + ' in \'' + gpuShader.name + '\' compilation failed.'); + console.error(`${shaderTypeStr} in '${gpuShader.name}' compilation failed.`); console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, () => `\n${lineNumber++} `)); console.error(gl.getShaderInfoLog(gpuStage.glShader)); @@ -1555,9 +1556,9 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb } if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { - console.info('Shader \'' + gpuShader.name + '\' compilation succeeded.'); + console.info(`Shader '${gpuShader.name}' compilation succeeded.`); } else { - console.error('Failed to link shader \'' + gpuShader.name + '\'.'); + console.error(`Failed to link shader '${gpuShader.name}'.`); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); return; } @@ -1605,7 +1606,6 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb gpuShader.glBlocks = new Array(activeBlockCount); for (let b = 0; b < activeBlockCount; ++b) { - blockName = gl.getActiveUniformBlockName(gpuShader.glProgram, b)!; const nameOffset = blockName.indexOf('['); if (nameOffset !== -1) { @@ -1666,8 +1666,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb // texture unit index mapping optimization const glActiveSamplers: IWebGL2GPUUniformSampler[] = []; const glActiveSamplerLocations: WebGLUniformLocation[] = []; - const bindingMappingInfo = device.bindingMappingInfo; - const texUnitCacheMap = device.stateCache.texUnitCacheMap; + const { bindingMappingInfo } = device; + const { texUnitCacheMap } = device.stateCache; let flexibleSetBaseOffset = 0; for (let i = 0; i < gpuShader.blocks.length; ++i) { @@ -1686,7 +1686,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb } if (texUnitCacheMap[sampler.name] === undefined) { let binding = sampler.binding + bindingMappingInfo.samplerOffsets[sampler.set] + arrayOffset; - if (sampler.set === bindingMappingInfo.flexibleSet) binding -= flexibleSetBaseOffset; + if (sampler.set === bindingMappingInfo.flexibleSet) { binding -= flexibleSetBaseOffset; } texUnitCacheMap[sampler.name] = binding % device.maxTextureUnits; arrayOffset += sampler.count - 1; } @@ -1717,7 +1717,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2Device, gpuShader: IWeb if (!glSampler.glLoc) { glSampler.glLoc = glActiveSamplerLocations[i]; - while (usedTexUnits[unitIdx]) unitIdx++; + while (usedTexUnits[unitIdx]) { unitIdx++; } for (let t = 0; t < glSampler.count; ++t) { while (usedTexUnits[unitIdx]) { unitIdx = (unitIdx + 1) % device.maxTextureUnits; @@ -1757,8 +1757,7 @@ export function WebGL2CmdFuncDestroyShader (device: WebGL2Device, gpuShader: IWe } export function WebGL2CmdFuncCreateInputAssember (device: WebGL2Device, gpuInputAssembler: IWebGL2GPUInputAssembler) { - - const gl = device.gl; + const { gl } = device; gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length); @@ -1773,7 +1772,7 @@ export function WebGL2CmdFuncCreateInputAssember (device: WebGL2Device, gpuInput const gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; const glType = GFXFormatToWebGLType(attrib.format, gl); - const size = FormatInfos[attrib.format].size; + const { size } = FormatInfos[attrib.format]; gpuInputAssembler.glAttribs[i] = { name: attrib.name, @@ -1824,9 +1823,9 @@ export function WebGL2CmdFuncBeginRenderPass ( renderArea: Rect, clearColors: Color[], clearDepth: number, - clearStencil: number) { - - const gl = device.gl; + clearStencil: number, +) { + const { gl } = device; const cache = device.stateCache; let clears: GLbitfield = 0; @@ -1845,11 +1844,10 @@ export function WebGL2CmdFuncBeginRenderPass ( } } - if (cache.viewport.left !== renderArea.x || - cache.viewport.top !== renderArea.y || - cache.viewport.width !== renderArea.width || - cache.viewport.height !== renderArea.height) { - + if (cache.viewport.left !== renderArea.x + || cache.viewport.top !== renderArea.y + || cache.viewport.width !== renderArea.width + || cache.viewport.height !== renderArea.height) { gl.viewport(renderArea.x, renderArea.y, renderArea.width, renderArea.height); cache.viewport.left = renderArea.x; @@ -1858,11 +1856,10 @@ export function WebGL2CmdFuncBeginRenderPass ( cache.viewport.height = renderArea.height; } - if (cache.scissorRect.x !== renderArea.x || - cache.scissorRect.y !== renderArea.y || - cache.scissorRect.width !== renderArea.width || - cache.scissorRect.height !== renderArea.height) { - + if (cache.scissorRect.x !== renderArea.x + || cache.scissorRect.y !== renderArea.y + || cache.scissorRect.width !== renderArea.width + || cache.scissorRect.height !== renderArea.height) { gl.scissor(renderArea.x, renderArea.y, renderArea.width, renderArea.height); cache.scissorRect.x = renderArea.x; @@ -1878,80 +1875,79 @@ export function WebGL2CmdFuncBeginRenderPass ( if (colorAttachment.format !== Format.UNKNOWN) { switch (colorAttachment.loadOp) { - case LoadOp.LOAD: break; // GL default behavior - case LoadOp.CLEAR: { - if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) { - gl.colorMask(true, true, true, true); - } + case LoadOp.LOAD: break; // GL default behavior + case LoadOp.CLEAR: { + if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) { + gl.colorMask(true, true, true, true); + } - if (!gpuFramebuffer.isOffscreen) { - const clearColor = clearColors[0]; - gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w); - clears |= gl.COLOR_BUFFER_BIT; - } else { - _f32v4[0] = clearColors[j].x; - _f32v4[1] = clearColors[j].y; - _f32v4[2] = clearColors[j].z; - _f32v4[3] = clearColors[j].w; - gl.clearBufferfv(gl.COLOR, j, _f32v4); - } - break; + if (!gpuFramebuffer.isOffscreen) { + const clearColor = clearColors[0]; + gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w); + clears |= gl.COLOR_BUFFER_BIT; + } else { + _f32v4[0] = clearColors[j].x; + _f32v4[1] = clearColors[j].y; + _f32v4[2] = clearColors[j].z; + _f32v4[3] = clearColors[j].w; + gl.clearBufferfv(gl.COLOR, j, _f32v4); } - case LoadOp.DISCARD: { - // invalidate the framebuffer - gfxStateCache.invalidateAttachments.push(gl.COLOR_ATTACHMENT0 + j); - break; - } - default: + break; + } + case LoadOp.DISCARD: { + // invalidate the framebuffer + gfxStateCache.invalidateAttachments.push(gl.COLOR_ATTACHMENT0 + j); + break; + } + default: } } } // if (curGPURenderPass) if (gpuRenderPass.depthStencilAttachment) { - if (gpuRenderPass.depthStencilAttachment.format !== Format.UNKNOWN) { switch (gpuRenderPass.depthStencilAttachment.depthLoadOp) { - case LoadOp.LOAD: break; // GL default behavior - case LoadOp.CLEAR: { - if (!cache.dss.depthWrite) { - gl.depthMask(true); - } - - gl.clearDepth(clearDepth); - - clears |= gl.DEPTH_BUFFER_BIT; - break; + case LoadOp.LOAD: break; // GL default behavior + case LoadOp.CLEAR: { + if (!cache.dss.depthWrite) { + gl.depthMask(true); } - case LoadOp.DISCARD: { - // invalidate the framebuffer - gfxStateCache.invalidateAttachments.push(gl.DEPTH_ATTACHMENT); - break; - } - default: + + gl.clearDepth(clearDepth); + + clears |= gl.DEPTH_BUFFER_BIT; + break; + } + case LoadOp.DISCARD: { + // invalidate the framebuffer + gfxStateCache.invalidateAttachments.push(gl.DEPTH_ATTACHMENT); + break; + } + default: } if (FormatInfos[gpuRenderPass.depthStencilAttachment.format].hasStencil) { switch (gpuRenderPass.depthStencilAttachment.stencilLoadOp) { - case LoadOp.LOAD: break; // GL default behavior - case LoadOp.CLEAR: { - if (!cache.dss.stencilWriteMaskFront) { - gl.stencilMaskSeparate(gl.FRONT, 0xffff); - } - - if (!cache.dss.stencilWriteMaskBack) { - gl.stencilMaskSeparate(gl.BACK, 0xffff); - } - - gl.clearStencil(clearStencil); - clears |= gl.STENCIL_BUFFER_BIT; - break; + case LoadOp.LOAD: break; // GL default behavior + case LoadOp.CLEAR: { + if (!cache.dss.stencilWriteMaskFront) { + gl.stencilMaskSeparate(gl.FRONT, 0xffff); } - case LoadOp.DISCARD: { - // invalidate the framebuffer - gfxStateCache.invalidateAttachments.push(gl.STENCIL_ATTACHMENT); - break; + + if (!cache.dss.stencilWriteMaskBack) { + gl.stencilMaskSeparate(gl.BACK, 0xffff); } - default: + + gl.clearStencil(clearStencil); + clears |= gl.STENCIL_BUFFER_BIT; + break; + } + case LoadOp.DISCARD: { + // invalidate the framebuffer + gfxStateCache.invalidateAttachments.push(gl.STENCIL_ATTACHMENT); + break; + } + default: } } } @@ -1967,7 +1963,6 @@ export function WebGL2CmdFuncBeginRenderPass ( // restore states if (clears & gl.COLOR_BUFFER_BIT) { - const colorMask = cache.bs.targets[0].blendColorMask; if (colorMask !== ColorMask.ALL) { const r = (colorMask & ColorMask.R) !== ColorMask.NONE; @@ -1978,8 +1973,8 @@ export function WebGL2CmdFuncBeginRenderPass ( } } - if ((clears & gl.DEPTH_BUFFER_BIT) && - !cache.dss.depthWrite) { + if ((clears & gl.DEPTH_BUFFER_BIT) + && !cache.dss.depthWrite) { gl.depthMask(false); } @@ -2008,9 +2003,9 @@ export function WebGL2CmdFuncBindStates ( blendConstants: number[], depthBounds: IWebGL2DepthBounds | null, stencilWriteMask: IWebGL2StencilWriteMask | null, - stencilCompareMask: IWebGL2StencilCompareMask | null) { - - const gl = device.gl; + stencilCompareMask: IWebGL2StencilCompareMask | null, +) { + const { gl } = device; const cache = device.stateCache; const gpuShader = gpuPipelineState && gpuPipelineState.gpuShader; @@ -2022,8 +2017,7 @@ export function WebGL2CmdFuncBindStates ( gfxStateCache.glPrimitive = gpuPipelineState.glPrimitive; if (gpuShader) { - - const glProgram = gpuShader.glProgram; + const { glProgram } = gpuShader; if (cache.glProgram !== glProgram) { gl.useProgram(glProgram); cache.glProgram = glProgram; @@ -2032,26 +2026,25 @@ export function WebGL2CmdFuncBindStates ( } // rasterizer state - const rs = gpuPipelineState.rs; + const { rs } = gpuPipelineState; if (rs) { - if (cache.rs.cullMode !== rs.cullMode) { switch (rs.cullMode) { - case CullMode.NONE: { - gl.disable(gl.CULL_FACE); - break; - } - case CullMode.FRONT: { - gl.enable(gl.CULL_FACE); - gl.cullFace(gl.FRONT); - break; - } - case CullMode.BACK: { - gl.enable(gl.CULL_FACE); - gl.cullFace(gl.BACK); - break; - } - default: + case CullMode.NONE: { + gl.disable(gl.CULL_FACE); + break; + } + case CullMode.FRONT: { + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.FRONT); + break; + } + case CullMode.BACK: { + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.BACK); + break; + } + default: } device.stateCache.rs.cullMode = rs.cullMode; @@ -2063,8 +2056,8 @@ export function WebGL2CmdFuncBindStates ( device.stateCache.rs.isFrontFaceCCW = isFrontFaceCCW; } - if ((device.stateCache.rs.depthBias !== rs.depthBias) || - (device.stateCache.rs.depthBiasSlop !== rs.depthBiasSlop)) { + if ((device.stateCache.rs.depthBias !== rs.depthBias) + || (device.stateCache.rs.depthBiasSlop !== rs.depthBiasSlop)) { gl.polygonOffset(rs.depthBias, rs.depthBiasSlop); device.stateCache.rs.depthBias = rs.depthBias; device.stateCache.rs.depthBiasSlop = rs.depthBiasSlop; @@ -2074,13 +2067,11 @@ export function WebGL2CmdFuncBindStates ( gl.lineWidth(rs.lineWidth); device.stateCache.rs.lineWidth = rs.lineWidth; } - } // rasterizater state // depth-stencil state - const dss = gpuPipelineState.dss; + const { dss } = gpuPipelineState; if (dss) { - if (cache.dss.depthTest !== dss.depthTest) { if (dss.depthTest) { gl.enable(gl.DEPTH_TEST); @@ -2101,8 +2092,8 @@ export function WebGL2CmdFuncBindStates ( } // front - if ((cache.dss.stencilTestFront !== dss.stencilTestFront) || - (cache.dss.stencilTestBack !== dss.stencilTestBack)) { + if ((cache.dss.stencilTestFront !== dss.stencilTestFront) + || (cache.dss.stencilTestBack !== dss.stencilTestBack)) { if (dss.stencilTestFront || dss.stencilTestBack) { gl.enable(gl.STENCIL_TEST); } else { @@ -2112,30 +2103,30 @@ export function WebGL2CmdFuncBindStates ( cache.dss.stencilTestBack = dss.stencilTestBack; } - if ((cache.dss.stencilFuncFront !== dss.stencilFuncFront) || - (cache.dss.stencilRefFront !== dss.stencilRefFront) || - (cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront)) { - + if ((cache.dss.stencilFuncFront !== dss.stencilFuncFront) + || (cache.dss.stencilRefFront !== dss.stencilRefFront) + || (cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront)) { gl.stencilFuncSeparate( gl.FRONT, WebGLCmpFuncs[dss.stencilFuncFront], dss.stencilRefFront, - dss.stencilReadMaskFront); + dss.stencilReadMaskFront, + ); cache.dss.stencilFuncFront = dss.stencilFuncFront; cache.dss.stencilRefFront = dss.stencilRefFront; cache.dss.stencilReadMaskFront = dss.stencilReadMaskFront; } - if ((cache.dss.stencilFailOpFront !== dss.stencilFailOpFront) || - (cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront) || - (cache.dss.stencilPassOpFront !== dss.stencilPassOpFront)) { - + if ((cache.dss.stencilFailOpFront !== dss.stencilFailOpFront) + || (cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront) + || (cache.dss.stencilPassOpFront !== dss.stencilPassOpFront)) { gl.stencilOpSeparate( gl.FRONT, WebGLStencilOps[dss.stencilFailOpFront], WebGLStencilOps[dss.stencilZFailOpFront], - WebGLStencilOps[dss.stencilPassOpFront]); + WebGLStencilOps[dss.stencilPassOpFront], + ); cache.dss.stencilFailOpFront = dss.stencilFailOpFront; cache.dss.stencilZFailOpFront = dss.stencilZFailOpFront; @@ -2148,30 +2139,30 @@ export function WebGL2CmdFuncBindStates ( } // back - if ((cache.dss.stencilFuncBack !== dss.stencilFuncBack) || - (cache.dss.stencilRefBack !== dss.stencilRefBack) || - (cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack)) { - + if ((cache.dss.stencilFuncBack !== dss.stencilFuncBack) + || (cache.dss.stencilRefBack !== dss.stencilRefBack) + || (cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack)) { gl.stencilFuncSeparate( gl.BACK, WebGLCmpFuncs[dss.stencilFuncBack], dss.stencilRefBack, - dss.stencilReadMaskBack); + dss.stencilReadMaskBack, + ); cache.dss.stencilFuncBack = dss.stencilFuncBack; cache.dss.stencilRefBack = dss.stencilRefBack; cache.dss.stencilReadMaskBack = dss.stencilReadMaskBack; } - if ((cache.dss.stencilFailOpBack !== dss.stencilFailOpBack) || - (cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack) || - (cache.dss.stencilPassOpBack !== dss.stencilPassOpBack)) { - + if ((cache.dss.stencilFailOpBack !== dss.stencilFailOpBack) + || (cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack) + || (cache.dss.stencilPassOpBack !== dss.stencilPassOpBack)) { gl.stencilOpSeparate( gl.BACK, WebGLStencilOps[dss.stencilFailOpBack], WebGLStencilOps[dss.stencilZFailOpBack], - WebGLStencilOps[dss.stencilPassOpBack]); + WebGLStencilOps[dss.stencilPassOpBack], + ); cache.dss.stencilFailOpBack = dss.stencilFailOpBack; cache.dss.stencilZFailOpBack = dss.stencilZFailOpBack; @@ -2185,9 +2176,8 @@ export function WebGL2CmdFuncBindStates ( } // depth-stencil state // blend state - const bs = gpuPipelineState.bs; + const { bs } = gpuPipelineState; if (bs) { - if (cache.bs.isA2C !== bs.isA2C) { if (bs.isA2C) { gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE); @@ -2197,11 +2187,10 @@ export function WebGL2CmdFuncBindStates ( cache.bs.isA2C = bs.isA2C; } - if ((cache.bs.blendColor.x !== bs.blendColor.x) || - (cache.bs.blendColor.y !== bs.blendColor.y) || - (cache.bs.blendColor.z !== bs.blendColor.z) || - (cache.bs.blendColor.w !== bs.blendColor.w)) { - + if ((cache.bs.blendColor.x !== bs.blendColor.x) + || (cache.bs.blendColor.y !== bs.blendColor.y) + || (cache.bs.blendColor.z !== bs.blendColor.z) + || (cache.bs.blendColor.w !== bs.blendColor.w)) { gl.blendColor(bs.blendColor.x, bs.blendColor.y, bs.blendColor.z, bs.blendColor.w); cache.bs.blendColor.x = bs.blendColor.x; @@ -2222,24 +2211,23 @@ export function WebGL2CmdFuncBindStates ( target0Cache.blend = target0.blend; } - if ((target0Cache.blendEq !== target0.blendEq) || - (target0Cache.blendAlphaEq !== target0.blendAlphaEq)) { - + if ((target0Cache.blendEq !== target0.blendEq) + || (target0Cache.blendAlphaEq !== target0.blendAlphaEq)) { gl.blendEquationSeparate(WebGLBlendOps[target0.blendEq], WebGLBlendOps[target0.blendAlphaEq]); target0Cache.blendEq = target0.blendEq; target0Cache.blendAlphaEq = target0.blendAlphaEq; } - if ((target0Cache.blendSrc !== target0.blendSrc) || - (target0Cache.blendDst !== target0.blendDst) || - (target0Cache.blendSrcAlpha !== target0.blendSrcAlpha) || - (target0Cache.blendDstAlpha !== target0.blendDstAlpha)) { - + if ((target0Cache.blendSrc !== target0.blendSrc) + || (target0Cache.blendDst !== target0.blendDst) + || (target0Cache.blendSrcAlpha !== target0.blendSrcAlpha) + || (target0Cache.blendDstAlpha !== target0.blendDstAlpha)) { gl.blendFuncSeparate( WebGLBlendFactors[target0.blendSrc], WebGLBlendFactors[target0.blendDst], WebGLBlendFactors[target0.blendSrcAlpha], - WebGLBlendFactors[target0.blendDstAlpha]); + WebGLBlendFactors[target0.blendDstAlpha], + ); target0Cache.blendSrc = target0.blendSrc; target0Cache.blendDst = target0.blendDst; @@ -2248,12 +2236,12 @@ export function WebGL2CmdFuncBindStates ( } if (target0Cache.blendColorMask !== target0.blendColorMask) { - gl.colorMask( (target0.blendColorMask & ColorMask.R) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.G) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.B) !== ColorMask.NONE, - (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE); + (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE, + ); target0Cache.blendColorMask = target0.blendColorMask; } @@ -2262,9 +2250,8 @@ export function WebGL2CmdFuncBindStates ( // bind descriptor sets if (gpuPipelineState && gpuPipelineState.gpuPipelineLayout && gpuShader) { - const blockLen = gpuShader.glBlocks.length; - const dynamicOffsetIndices = gpuPipelineState.gpuPipelineLayout.dynamicOffsetIndices; + const { dynamicOffsetIndices } = gpuPipelineState.gpuPipelineLayout; for (let j = 0; j < blockLen; j++) { const glBlock = gpuShader.glBlocks[j]; @@ -2280,10 +2267,10 @@ export function WebGL2CmdFuncBindStates ( const dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set]; const dynamicOffsetIndex = dynamicOffsetIndexSet && dynamicOffsetIndexSet[glBlock.binding]; let offset = gpuDescriptor.gpuBuffer.glOffset; - if (dynamicOffsetIndex >= 0) offset += dynamicOffsets[dynamicOffsetIndex]; + if (dynamicOffsetIndex >= 0) { offset += dynamicOffsets[dynamicOffsetIndex]; } - if (cache.glBindUBOs[glBlock.glBinding] !== gpuDescriptor.gpuBuffer.glBuffer || - cache.glBindUBOOffsets[glBlock.glBinding] !== offset) { + if (cache.glBindUBOs[glBlock.glBinding] !== gpuDescriptor.gpuBuffer.glBuffer + || cache.glBindUBOOffsets[glBlock.glBinding] !== offset) { if (offset) { gl.bindBufferRange(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer, offset, gpuDescriptor.gpuBuffer.size); @@ -2312,10 +2299,9 @@ export function WebGL2CmdFuncBindStates ( continue; } - if (gpuDescriptor.gpuTexture && - gpuDescriptor.gpuTexture.size > 0) { - - const gpuTexture = gpuDescriptor.gpuTexture; + if (gpuDescriptor.gpuTexture + && gpuDescriptor.gpuTexture.size > 0) { + const { gpuTexture } = gpuDescriptor; if (glTexUnit.glTexture !== gpuTexture.glTexture) { if (cache.texUnit !== texUnit) { gl.activeTexture(gl.TEXTURE0 + texUnit); @@ -2329,7 +2315,7 @@ export function WebGL2CmdFuncBindStates ( glTexUnit.glTexture = gpuTexture.glTexture; } - const gpuSampler = gpuDescriptor.gpuSampler; + const { gpuSampler } = gpuDescriptor; if (cache.glSamplerUnits[texUnit] !== gpuSampler.glSampler) { gl.bindSampler(texUnit, gpuSampler.glSampler); cache.glSamplerUnits[texUnit] = gpuSampler.glSampler; @@ -2342,8 +2328,8 @@ export function WebGL2CmdFuncBindStates ( } // bind descriptor sets // bind vertex/index buffer - if (gpuInputAssembler && gpuShader && - (isShaderChanged || gfxStateCache.gpuInputAssembler !== gpuInputAssembler)) { + if (gpuInputAssembler && gpuShader + && (isShaderChanged || gfxStateCache.gpuInputAssembler !== gpuInputAssembler)) { gfxStateCache.gpuInputAssembler = gpuInputAssembler; if (device.useVAO) { @@ -2469,167 +2455,166 @@ export function WebGL2CmdFuncBindStates ( for (let k = 0; k < dsLen; k++) { const dynamicState = gpuPipelineState.dynamicStates[k]; switch (dynamicState) { - case DynamicStateFlagBit.VIEWPORT: { - if (viewport) { - if (cache.viewport.left !== viewport.left || - cache.viewport.top !== viewport.top || - cache.viewport.width !== viewport.width || - cache.viewport.height !== viewport.height) { + case DynamicStateFlagBit.VIEWPORT: { + if (viewport) { + if (cache.viewport.left !== viewport.left + || cache.viewport.top !== viewport.top + || cache.viewport.width !== viewport.width + || cache.viewport.height !== viewport.height) { + gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height); - gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height); + cache.viewport.left = viewport.left; + cache.viewport.top = viewport.top; + cache.viewport.width = viewport.width; + cache.viewport.height = viewport.height; + } + } + break; + } + case DynamicStateFlagBit.SCISSOR: { + if (scissor) { + if (cache.scissorRect.x !== scissor.x + || cache.scissorRect.y !== scissor.y + || cache.scissorRect.width !== scissor.width + || cache.scissorRect.height !== scissor.height) { + gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height); - cache.viewport.left = viewport.left; - cache.viewport.top = viewport.top; - cache.viewport.width = viewport.width; - cache.viewport.height = viewport.height; + cache.scissorRect.x = scissor.x; + cache.scissorRect.y = scissor.y; + cache.scissorRect.width = scissor.width; + cache.scissorRect.height = scissor.height; + } + } + break; + } + case DynamicStateFlagBit.LINE_WIDTH: { + if (lineWidth) { + if (cache.rs.lineWidth !== lineWidth) { + gl.lineWidth(lineWidth); + cache.rs.lineWidth = lineWidth; + } + } + break; + } + case DynamicStateFlagBit.DEPTH_BIAS: { + if (depthBias) { + if ((cache.rs.depthBias !== depthBias.constantFactor) + || (cache.rs.depthBiasSlop !== depthBias.slopeFactor)) { + gl.polygonOffset(depthBias.constantFactor, depthBias.slopeFactor); + cache.rs.depthBias = depthBias.constantFactor; + cache.rs.depthBiasSlop = depthBias.slopeFactor; + } + } + break; + } + case DynamicStateFlagBit.BLEND_CONSTANTS: { + if ((cache.bs.blendColor.x !== blendConstants[0]) + || (cache.bs.blendColor.y !== blendConstants[1]) + || (cache.bs.blendColor.z !== blendConstants[2]) + || (cache.bs.blendColor.w !== blendConstants[3])) { + gl.blendColor(blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]); + + [cache.bs.blendColor.x, cache.bs.blendColor.y, cache.bs.blendColor.z, cache.bs.blendColor.w] = blendConstants; + } + break; + } + case DynamicStateFlagBit.STENCIL_WRITE_MASK: { + if (stencilWriteMask) { + switch (stencilWriteMask.face) { + case StencilFace.FRONT: { + if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(gl.FRONT, stencilWriteMask.writeMask); + cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; } + break; } - break; - } - case DynamicStateFlagBit.SCISSOR: { - if (scissor) { - if (cache.scissorRect.x !== scissor.x || - cache.scissorRect.y !== scissor.y || - cache.scissorRect.width !== scissor.width || - cache.scissorRect.height !== scissor.height) { - - gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height); - - cache.scissorRect.x = scissor.x; - cache.scissorRect.y = scissor.y; - cache.scissorRect.width = scissor.width; - cache.scissorRect.height = scissor.height; + case StencilFace.BACK: { + if (cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(gl.BACK, stencilWriteMask.writeMask); + cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; } + break; } - break; - } - case DynamicStateFlagBit.LINE_WIDTH: { - if (lineWidth) { - if (cache.rs.lineWidth !== lineWidth) { - gl.lineWidth(lineWidth); - cache.rs.lineWidth = lineWidth; + case StencilFace.ALL: { + if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask + || cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { + gl.stencilMask(stencilWriteMask.writeMask); + cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; + cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; } + break; + } + default: } - break; } - case DynamicStateFlagBit.DEPTH_BIAS: { - if (depthBias) { - - if ((cache.rs.depthBias !== depthBias.constantFactor) || - (cache.rs.depthBiasSlop !== depthBias.slopeFactor)) { - gl.polygonOffset(depthBias.constantFactor, depthBias.slopeFactor); - cache.rs.depthBias = depthBias.constantFactor; - cache.rs.depthBiasSlop = depthBias.slopeFactor; + break; + } + case DynamicStateFlagBit.STENCIL_COMPARE_MASK: { + if (stencilCompareMask) { + switch (stencilCompareMask.face) { + case StencilFace.FRONT: { + if (cache.dss.stencilRefFront !== stencilCompareMask.reference + || cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + gl.FRONT, + WebGLCmpFuncs[cache.dss.stencilFuncFront], + stencilCompareMask.reference, + stencilCompareMask.compareMask, + ); + cache.dss.stencilRefFront = stencilCompareMask.reference; + cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; } + break; } - break; - } - case DynamicStateFlagBit.BLEND_CONSTANTS: { - if ((cache.bs.blendColor.x !== blendConstants[0]) || - (cache.bs.blendColor.y !== blendConstants[1]) || - (cache.bs.blendColor.z !== blendConstants[2]) || - (cache.bs.blendColor.w !== blendConstants[3])) { - - gl.blendColor(blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]); - - cache.bs.blendColor.x = blendConstants[0]; - cache.bs.blendColor.y = blendConstants[1]; - cache.bs.blendColor.z = blendConstants[2]; - cache.bs.blendColor.w = blendConstants[3]; - } - break; - } - case DynamicStateFlagBit.STENCIL_WRITE_MASK: { - if (stencilWriteMask) { - switch (stencilWriteMask.face) { - case StencilFace.FRONT: { - if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask) { - gl.stencilMaskSeparate(gl.FRONT, stencilWriteMask.writeMask); - cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; - } - break; - } - case StencilFace.BACK: { - if (cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { - gl.stencilMaskSeparate(gl.BACK, stencilWriteMask.writeMask); - cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; - } - break; - } - case StencilFace.ALL: { - if (cache.dss.stencilWriteMaskFront !== stencilWriteMask.writeMask || - cache.dss.stencilWriteMaskBack !== stencilWriteMask.writeMask) { - gl.stencilMask(stencilWriteMask.writeMask); - cache.dss.stencilWriteMaskFront = stencilWriteMask.writeMask; - cache.dss.stencilWriteMaskBack = stencilWriteMask.writeMask; - } - break; - } + case StencilFace.BACK: { + if (cache.dss.stencilRefBack !== stencilCompareMask.reference + || cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + gl.BACK, + WebGLCmpFuncs[cache.dss.stencilFuncBack], + stencilCompareMask.reference, + stencilCompareMask.compareMask, + ); + cache.dss.stencilRefBack = stencilCompareMask.reference; + cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; } + break; } - break; - } - case DynamicStateFlagBit.STENCIL_COMPARE_MASK: { - if (stencilCompareMask) { - switch (stencilCompareMask.face) { - case StencilFace.FRONT: { - if (cache.dss.stencilRefFront !== stencilCompareMask.reference || - cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask) { - gl.stencilFuncSeparate( - gl.FRONT, - WebGLCmpFuncs[cache.dss.stencilFuncFront], - stencilCompareMask.reference, - stencilCompareMask.compareMask); - cache.dss.stencilRefFront = stencilCompareMask.reference; - cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; - } - break; - } - case StencilFace.BACK: { - if (cache.dss.stencilRefBack !== stencilCompareMask.reference || - cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { - gl.stencilFuncSeparate( - gl.BACK, - WebGLCmpFuncs[cache.dss.stencilFuncBack], - stencilCompareMask.reference, - stencilCompareMask.compareMask); - cache.dss.stencilRefBack = stencilCompareMask.reference; - cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; - } - break; - } - case StencilFace.ALL: { - if (cache.dss.stencilRefFront !== stencilCompareMask.reference || - cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask || - cache.dss.stencilRefBack !== stencilCompareMask.reference || - cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { - gl.stencilFunc( - WebGLCmpFuncs[cache.dss.stencilFuncBack], - stencilCompareMask.reference, - stencilCompareMask.compareMask); - cache.dss.stencilRefFront = stencilCompareMask.reference; - cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; - cache.dss.stencilRefBack = stencilCompareMask.reference; - cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; - } - break; - } + case StencilFace.ALL: { + if (cache.dss.stencilRefFront !== stencilCompareMask.reference + || cache.dss.stencilReadMaskFront !== stencilCompareMask.compareMask + || cache.dss.stencilRefBack !== stencilCompareMask.reference + || cache.dss.stencilReadMaskBack !== stencilCompareMask.compareMask) { + gl.stencilFunc( + WebGLCmpFuncs[cache.dss.stencilFuncBack], + stencilCompareMask.reference, + stencilCompareMask.compareMask, + ); + cache.dss.stencilRefFront = stencilCompareMask.reference; + cache.dss.stencilReadMaskFront = stencilCompareMask.compareMask; + cache.dss.stencilRefBack = stencilCompareMask.reference; + cache.dss.stencilReadMaskBack = stencilCompareMask.compareMask; } + break; + } + default: } - break; } + break; + } + default: } // switch } // for } // update dynamic states } export function WebGL2CmdFuncDraw (device: WebGL2Device, drawInfo: DrawInfo) { - const gl = device.gl; + const { gl } = device; const { gpuInputAssembler, glPrimitive } = gfxStateCache; if (gpuInputAssembler) { if (gpuInputAssembler.gpuIndirectBuffer) { - const indirects = gpuInputAssembler.gpuIndirectBuffer.indirects; + const { indirects } = gpuInputAssembler.gpuIndirectBuffer; for (let k = 0; k < indirects.length; k++) { const subDrawInfo = indirects[k]; const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; @@ -2643,38 +2628,32 @@ export function WebGL2CmdFuncDraw (device: WebGL2Device, drawInfo: DrawInfo) { } else if (subDrawInfo.vertexCount > 0) { gl.drawArraysInstanced(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount, subDrawInfo.instanceCount); } - } else { - if (gpuBuffer) { - if (subDrawInfo.indexCount > 0) { - const offset = subDrawInfo.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, subDrawInfo.indexCount, gpuInputAssembler.glIndexType, offset); - } - } else if (subDrawInfo.vertexCount > 0) { - gl.drawArrays(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount); + } else if (gpuBuffer) { + if (subDrawInfo.indexCount > 0) { + const offset = subDrawInfo.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, subDrawInfo.indexCount, gpuInputAssembler.glIndexType, offset); } + } else if (subDrawInfo.vertexCount > 0) { + gl.drawArrays(glPrimitive, subDrawInfo.firstVertex, subDrawInfo.vertexCount); } } - } else { - if (drawInfo.instanceCount) { - if (gpuInputAssembler.gpuIndexBuffer) { - if (drawInfo.indexCount > 0) { - const offset = drawInfo.firstIndex * gpuInputAssembler.gpuIndexBuffer.stride; - gl.drawElementsInstanced(glPrimitive, drawInfo.indexCount, - gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount); - } - } else if (drawInfo.vertexCount > 0) { - gl.drawArraysInstanced(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount); - } - } else { - if (gpuInputAssembler.gpuIndexBuffer) { - if (drawInfo.indexCount > 0) { - const offset = drawInfo.firstIndex * gpuInputAssembler.gpuIndexBuffer.stride; - gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); - } - } else if (drawInfo.vertexCount > 0) { - gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount); + } else if (drawInfo.instanceCount) { + if (gpuInputAssembler.gpuIndexBuffer) { + if (drawInfo.indexCount > 0) { + const offset = drawInfo.firstIndex * gpuInputAssembler.gpuIndexBuffer.stride; + gl.drawElementsInstanced(glPrimitive, drawInfo.indexCount, + gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount); } + } else if (drawInfo.vertexCount > 0) { + gl.drawArraysInstanced(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount); } + } else if (gpuInputAssembler.gpuIndexBuffer) { + if (drawInfo.indexCount > 0) { + const offset = drawInfo.firstIndex * gpuInputAssembler.gpuIndexBuffer.stride; + gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); + } + } else if (drawInfo.vertexCount > 0) { + gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount); } } } @@ -2688,41 +2667,42 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2Device, cmdPackage: WebG const cmdId = cmdIds[cmd]++; switch (cmd) { - case WebGL2Cmd.BEGIN_RENDER_PASS: { - const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; - WebGL2CmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, - cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil); - break; - } - /* + case WebGL2Cmd.BEGIN_RENDER_PASS: { + const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; + WebGL2CmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, + cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil); + break; + } + /* case WebGL2Cmd.END_RENDER_PASS: { // WebGL 2.0 doesn't support store operation of attachments. // StoreOp.Store is the default GL behavior. break; } */ - case WebGL2Cmd.BIND_STATES: { - const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; - WebGL2CmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, - cmd2.viewport, cmd2.scissor, cmd2.lineWidth, cmd2.depthBias, cmd2.blendConstants, - cmd2.depthBounds, cmd2.stencilWriteMask, cmd2.stencilCompareMask); - break; - } - case WebGL2Cmd.DRAW: { - const cmd3 = cmdPackage.drawCmds.array[cmdId]; - WebGL2CmdFuncDraw(device, cmd3.drawInfo); - break; - } - case WebGL2Cmd.UPDATE_BUFFER: { - const cmd4 = cmdPackage.updateBufferCmds.array[cmdId]; - WebGL2CmdFuncUpdateBuffer(device, cmd4.gpuBuffer as IWebGL2GPUBuffer, cmd4.buffer as BufferSource, cmd4.offset, cmd4.size); - break; - } - case WebGL2Cmd.COPY_BUFFER_TO_TEXTURE: { - const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; - WebGL2CmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture as IWebGL2GPUTexture, cmd5.regions); - break; - } + case WebGL2Cmd.BIND_STATES: { + const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; + WebGL2CmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, + cmd2.viewport, cmd2.scissor, cmd2.lineWidth, cmd2.depthBias, cmd2.blendConstants, + cmd2.depthBounds, cmd2.stencilWriteMask, cmd2.stencilCompareMask); + break; + } + case WebGL2Cmd.DRAW: { + const cmd3 = cmdPackage.drawCmds.array[cmdId]; + WebGL2CmdFuncDraw(device, cmd3.drawInfo); + break; + } + case WebGL2Cmd.UPDATE_BUFFER: { + const cmd4 = cmdPackage.updateBufferCmds.array[cmdId]; + WebGL2CmdFuncUpdateBuffer(device, cmd4.gpuBuffer as IWebGL2GPUBuffer, cmd4.buffer as BufferSource, cmd4.offset, cmd4.size); + break; + } + case WebGL2Cmd.COPY_BUFFER_TO_TEXTURE: { + const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; + WebGL2CmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture as IWebGL2GPUTexture, cmd5.regions); + break; + } + default: } // switch } // for } @@ -2731,9 +2711,9 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( device: WebGL2Device, texImages: TexImageSource[], gpuTexture: IWebGL2GPUTexture, - regions: BufferTextureCopy[]) { - - const gl = device.gl; + regions: BufferTextureCopy[], +) { + const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture); @@ -2744,30 +2724,30 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( let f = 0; switch (gpuTexture.glTarget) { - case gl.TEXTURE_2D: { - for (let k = 0; k < regions.length; k++) { - const region = regions[k]; - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + case gl.TEXTURE_2D: { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; + gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, + gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); + } + break; + } + case gl.TEXTURE_CUBE_MAP: { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { + gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); } - break; - } - case gl.TEXTURE_CUBE_MAP: { - for (let k = 0; k < regions.length; k++) { - const region = regions[k]; - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, - gpuTexture.glFormat, gpuTexture.glType, texImages[n++]); - } - } - break; - } - default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); } + break; + } + default: { + console.error('Unsupported GL texture type, copy buffer to texture failed.'); + } } if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) { @@ -2779,9 +2759,9 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( device: WebGL2Device, buffers: ArrayBufferView[], gpuTexture: IWebGL2GPUTexture, - regions: BufferTextureCopy[]) { - - const gl = device.gl; + regions: BufferTextureCopy[], +) { + const { gl } = device; const glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture); @@ -2793,63 +2773,59 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( let h = 1; let f = 0; const fmtInfo: FormatInfo = FormatInfos[gpuTexture.format]; - const isCompressed = fmtInfo.isCompressed; + const { isCompressed } = fmtInfo; switch (gpuTexture.glTarget) { - case gl.TEXTURE_2D: { - for (let k = 0; k < regions.length; k++) { - const region = regions[k]; + case gl.TEXTURE_2D: { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; + w = region.texExtent.width; + h = region.texExtent.height; + const pixels = buffers[n++]; + if (!isCompressed) { + gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, pixels); + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + } else { + gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + gpuTexture.glInternalFmt, w, h, 0, pixels); + } + } + break; + } + case gl.TEXTURE_CUBE_MAP: { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { w = region.texExtent.width; h = region.texExtent.height; + const pixels = buffers[n++]; + if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, gpuTexture.glType, pixels); + } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - } else { - gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); - } + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, + gpuTexture.glInternalFmt, w, h, 0, pixels); } } - break; - } - case gl.TEXTURE_CUBE_MAP: { - for (let k = 0; k < regions.length; k++) { - const region = regions[k]; - const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; - for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - - const pixels = buffers[n++]; - - if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); - } else { - if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); - } else { - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); - } - } - } - } - break; - } - default: { - console.error('Unsupported GL texture type, copy buffer to texture failed.'); } + break; + } + default: { + console.error('Unsupported GL texture type, copy buffer to texture failed.'); + } } if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) { @@ -2863,8 +2839,9 @@ export function WebGL2CmdFuncBlitFramebuffer ( dst: IWebGL2GPUFramebuffer, srcRect: Rect, dstRect: Rect, - filter: Filter) { - const gl = device.gl; + filter: Filter, +) { + const { gl } = device; if (device.stateCache.glReadFramebuffer !== src.glFramebuffer) { gl.bindFramebuffer(gl.READ_FRAMEBUFFER, src.glFramebuffer); @@ -2893,7 +2870,8 @@ export function WebGL2CmdFuncBlitFramebuffer ( gl.blitFramebuffer( srcRect.x, srcRect.y, srcRect.x + srcRect.width, srcRect.y + srcRect.height, dstRect.x, dstRect.y, dstRect.x + dstRect.width, dstRect.y + dstRect.height, - mask, glFilter); + mask, glFilter, + ); if (rebindFBO) { gl.bindFramebuffer(gl.FRAMEBUFFER, device.stateCache.glFramebuffer); diff --git a/cocos/core/global-exports.ts b/cocos/core/global-exports.ts index 1c3fe1cbf8..95d2b8d5b5 100644 --- a/cocos/core/global-exports.ts +++ b/cocos/core/global-exports.ts @@ -50,7 +50,6 @@ import { VIVO, } from 'internal:constants'; -// @ts-ignore const _global = typeof window === 'undefined' ? global : window; /** diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index 9a3383dc7e..6cf6164d60 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -314,7 +314,7 @@ export class Color extends ValueType { * @zh 用十六进制颜色字符串中构造颜色。 * @param hexString Hexadecimal color string. */ - // tslint:disable-next-line: unified-signatures + constructor (hexString: string); /** @@ -466,8 +466,8 @@ export class Color extends ValueType { (this.g < 16 ? prefix : '') + (this.g).toString(16), (this.b < 16 ? prefix : '') + (this.b).toString(16), ]; - let i = -1; - if ( fmt === '#rgb' ) { + const i = -1; + if (fmt === '#rgb') { hex[0] = hex[0][0]; hex[1] = hex[1][0]; hex[2] = hex[2][0]; @@ -617,7 +617,7 @@ export class Color extends ValueType { */ public set(other: Color): Color; public set(r?: number, g?: number, b?: number, a?: number): Color; - public set(r?: number | Color, g?: number, b?: number, a?: number): Color { + public set (r?: number | Color, g?: number, b?: number, a?: number): Color { if (typeof r === 'object') { if (r._val != null) { this._val = r._val; diff --git a/cocos/core/math/mat3.ts b/cocos/core/math/mat3.ts index edae6e387b..48fdc40d9a 100644 --- a/cocos/core/math/mat3.ts +++ b/cocos/core/math/mat3.ts @@ -40,7 +40,7 @@ import { legacyCC } from '../global-exports'; * @en Mathematical 3x3 matrix. * @zh 表示三维(3x3)矩阵。 */ -// tslint:disable:one-variable-per-declaration + export class Mat3 extends ValueType { public static IDENTITY = Object.freeze(new Mat3()); @@ -692,9 +692,9 @@ export class Mat3 extends ValueType { m06?: number, m07?: number, m08?: number); constructor ( - m00: number | Mat3 = 1, m01: number = 0, m02: number = 0, - m03: number = 0, m04: number = 1, m05: number = 0, - m06: number = 0, m07: number = 0, m08: number = 1 ) { + m00: number | Mat3 = 1, m01 = 0, m02 = 0, + m03 = 0, m04 = 1, m05 = 0, + m06 = 0, m07 = 0, m08 = 1) { super(); if (typeof m00 === 'object') { this.m00 = m00.m00; this.m01 = m00.m01; this.m02 = m00.m02; @@ -736,9 +736,9 @@ export class Mat3 extends ValueType { m03?: number, m04?: number, m05?: number, m06?: number, m07?: number, m08?: number); - public set (m00: number | Mat3 = 1, m01: number = 0, m02: number = 0, - m03: number = 0, m04: number = 1, m05: number = 0, - m06: number = 0, m07: number = 0, m08: number = 1 ) { + public set (m00: number | Mat3 = 1, m01 = 0, m02 = 0, + m03 = 0, m04 = 1, m05 = 0, + m06 = 0, m07 = 0, m08 = 1) { 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; diff --git a/cocos/core/math/mat4.ts b/cocos/core/math/mat4.ts index c671cf3478..3f6b4084c6 100644 --- a/cocos/core/math/mat4.ts +++ b/cocos/core/math/mat4.ts @@ -48,7 +48,7 @@ export const preTransforms = Object.freeze([ * @en Mathematical 4x4 matrix. * @zh 表示四维(4x4)矩阵。 */ -// tslint:disable:one-variable-per-declaration + export class Mat4 extends ValueType { public static IDENTITY = Object.freeze(new Mat4()); diff --git a/cocos/core/memop/sort.ts b/cocos/core/memop/sort.ts index 048eb05af3..c40242715b 100644 --- a/cocos/core/memop/sort.ts +++ b/cocos/core/memop/sort.ts @@ -5,7 +5,7 @@ * @hidden */ -// tslint:disable:no-shadowed-variable + function _compare (a, b) { return a - b; diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index 71d8f795d9..7716704c74 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -12,12 +12,12 @@ import { BindingMappingInfo, DescriptorType, Type, ShaderStageFlagBit, DescriptorSetLayoutBinding, Uniform, UniformBlock, UniformSampler } from '../gfx'; import { Camera } from '../renderer/scene'; -// tslint:disable: max-line-length -export const PIPELINE_FLOW_FORWARD: string = 'ForwardFlow'; -export const PIPELINE_FLOW_SHADOW: string = 'ShadowFlow'; -export const PIPELINE_FLOW_SMAA: string = 'SMAAFlow'; -export const PIPELINE_FLOW_TONEMAP: string = 'ToneMapFlow'; + +export const PIPELINE_FLOW_FORWARD = 'ForwardFlow'; +export const PIPELINE_FLOW_SHADOW = 'ShadowFlow'; +export const PIPELINE_FLOW_SMAA = 'SMAAFlow'; +export const PIPELINE_FLOW_TONEMAP = 'ToneMapFlow'; /** * @en The predefined render pass stage ids diff --git a/cocos/core/pipeline/render-additive-light-queue.ts b/cocos/core/pipeline/render-additive-light-queue.ts index d023e6ad83..853236bd6e 100644 --- a/cocos/core/pipeline/render-additive-light-queue.ts +++ b/cocos/core/pipeline/render-additive-light-queue.ts @@ -3,26 +3,30 @@ * @module pipeline */ -import { IRenderObject, UBOForwardLight, SetIndex } from './define'; -import { Light, LightType } from '../renderer/scene/light'; +import { BatchedBuffer } from './batched-buffer'; +import { BatchingSchemes } from '../renderer/core/pass'; +import { ForwardPipeline } from './forward/forward-pipeline'; +import { InstancedBuffer } from './instanced-buffer'; +import { Model } from '../renderer/scene/model'; +import { PipelineStateManager } from './pipeline-state-manager'; +import { Pool } from '../memop'; +import { RenderBatchedQueue } from './render-batched-queue'; +import { RenderInstancedQueue } from './render-instanced-queue'; +import { RenderView } from './render-view'; import { SphereLight } from '../renderer/scene/sphere-light'; import { SpotLight } from '../renderer/scene/spot-light'; -import { BatchingSchemes } from '../renderer/core/pass' -import { Model } from '../renderer/scene/model'; import { SubModel } from '../renderer/scene/submodel'; -import { PipelineStateManager } from './pipeline-state-manager'; -import { DSPool, ShaderPool, PassView, PassPool, SubModelPool, SubModelView, ShaderHandle } from '../renderer/core/memory-pools'; -import { Vec3, nextPow2 } from '../../core/math'; -import { RenderView } from './render-view'; -import { sphere, intersect } from '../geometry'; -import { Device, RenderPass, Buffer, BufferUsageBit, MemoryUsageBit, BufferInfo, BufferViewInfo, CommandBuffer } from '../gfx'; -import { Pool } from '../memop'; -import { InstancedBuffer } from './instanced-buffer'; -import { BatchedBuffer } from './batched-buffer'; -import { ForwardPipeline } from './forward/forward-pipeline'; -import { RenderInstancedQueue } from './render-instanced-queue'; -import { RenderBatchedQueue } from './render-batched-queue'; import { getPhaseID } from './pass-phase'; +import { + Buffer, BufferInfo, BufferUsageBit, BufferViewInfo, CommandBuffer, Device, MemoryUsageBit, RenderPass, +} from '../gfx'; +import { + DSPool, PassPool, PassView, ShaderHandle, ShaderPool, SubModelPool, SubModelView, +} from '../renderer/core/memory-pools'; +import { IRenderObject, SetIndex, UBOForwardLight } from './define'; +import { Light, LightType } from '../renderer/scene/light'; +import { Vec3, nextPow2 } from '../math'; +import { intersect, sphere } from '../geometry'; interface IAdditiveLightPass { subModel: SubModel; @@ -42,8 +46,8 @@ function cullSphereLight (light: SphereLight, model: Model) { } function cullSpotLight (light: SpotLight, model: Model) { - return !!(model.worldBounds && - (!intersect.aabb_aabb(model.worldBounds, light.aabb) || !intersect.aabb_frustum(model.worldBounds, light.frustum))); + return !!(model.worldBounds + && (!intersect.aabb_aabb(model.worldBounds, light.aabb) || !intersect.aabb_frustum(model.worldBounds, light.frustum))); } const _phaseID = getPhaseID('forward-add'); @@ -52,7 +56,7 @@ function getLightPassIndices (subModels: SubModel[], lightPassIndices: number[]) lightPassIndices.length = 0; let hasValidLightPass = false; for (let j = 0; j < subModels.length; j++) { - const passes = subModels[j].passes; + const { passes } = subModels[j]; let lightPassIndex = -1; for (let k = 0; k < passes.length; k++) { if (passes[k].phase === _phaseID) { @@ -70,24 +74,35 @@ function getLightPassIndices (subModels: SubModel[], lightPassIndices: number[]) * @zh 叠加光照队列。 */ export class RenderAdditiveLightQueue { - private _device: Device; + private _validLights: Light[] = []; + private _lightPasses: IAdditiveLightPass[] = []; private _lightBufferCount = 16; + private _lightBufferStride: number; + private _lightBufferElementCount: number; + private _lightBuffer: Buffer; + private _firstlightBufferView: Buffer; + private _lightBufferData: Float32Array; private _isHDR: boolean; + private _fpScale: number; + private _renderObjects: IRenderObject[]; + private _instancedQueue: RenderInstancedQueue; + private _batchedQueue: RenderBatchedQueue; - private _lightMeterScale: number = 10000.0; + + private _lightMeterScale = 10000.0; constructor (pipeline: ForwardPipeline) { this._device = pipeline.device; @@ -113,9 +128,8 @@ export class RenderAdditiveLightQueue { } public gatherLightPasses (view: RenderView, cmdBuff: CommandBuffer) { - const validLights = this._validLights; - const sphereLights = view.camera.scene!.sphereLights; + const { sphereLights } = view.camera.scene!; this._instancedQueue.clear(); this._batchedQueue.clear(); @@ -135,7 +149,7 @@ export class RenderAdditiveLightQueue { validLights.push(light); } } - const spotLights = view.camera.scene!.spotLights; + const { spotLights } = view.camera.scene!; for (let i = 0; i < spotLights.length; i++) { const light = spotLights[i]; sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); @@ -144,41 +158,42 @@ export class RenderAdditiveLightQueue { } } - if (!validLights.length) return; + if (!validLights.length) { return; } this._updateUBOs(view, cmdBuff); for (let i = 0; i < this._renderObjects.length; i++) { const ro = this._renderObjects[i]; - const model = ro.model; - const subModels = model.subModels; - if (!getLightPassIndices(subModels, _lightPassIndices)) continue; + const { model } = ro; + const { subModels } = model; + if (!getLightPassIndices(subModels, _lightPassIndices)) { continue; } _lightIndices.length = 0; for (let l = 0; l < validLights.length; l++) { const light = validLights[l]; let isCulled = false; switch (light.type) { - case LightType.SPHERE: - isCulled = cullSphereLight(light as SphereLight, model); - break; - case LightType.SPOT: - isCulled = cullSpotLight(light as SpotLight, model); - break; + case LightType.SPHERE: + isCulled = cullSphereLight(light as SphereLight, model); + break; + case LightType.SPOT: + isCulled = cullSpotLight(light as SpotLight, model); + break; + default: } if (!isCulled) { _lightIndices.push(l); } } - if (!_lightIndices.length) continue; + if (!_lightIndices.length) { continue; } for (let j = 0; j < subModels.length; j++) { const lightPassIdx = _lightPassIndices[j]; - if (lightPassIdx < 0) continue; + if (lightPassIdx < 0) { continue; } const subModel = subModels[j]; const pass = subModel.passes[lightPassIdx]; - const batchingScheme = pass.batchingScheme; + const { batchingScheme } = pass; subModel.descriptorSet.bindBuffer(UBOForwardLight.BINDING, this._firstlightBufferView); subModel.descriptorSet.update(); @@ -240,7 +255,7 @@ export class RenderAdditiveLightQueue { } protected _updateUBOs (view: RenderView, cmdBuff: CommandBuffer) { - const exposure = view.camera.exposure; + const { exposure } = view.camera; if (this._validLights.length > this._lightBufferCount) { this._firstlightBufferView.destroy(); @@ -252,64 +267,62 @@ export class RenderAdditiveLightQueue { this._firstlightBufferView.initialize(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE)); } - for(let l = 0, offset = 0; l < this._validLights.length; l++, offset += this._lightBufferElementCount) { + for (let l = 0, offset = 0; l < this._validLights.length; l++, offset += this._lightBufferElementCount) { const light = this._validLights[l]; switch (light.type) { - case LightType.SPHERE: - const sphereLit = light as SphereLight; - Vec3.toArray(_vec4Array, sphereLit.position); - _vec4Array[3] = 0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); + case LightType.SPHERE: + Vec3.toArray(_vec4Array, (light as SphereLight).position); + _vec4Array[3] = 0; + this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); - _vec4Array[0] = sphereLit.size; - _vec4Array[1] = sphereLit.range; - _vec4Array[2] = 0.0; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); + _vec4Array[0] = (light as SphereLight).size; + _vec4Array[1] = (light as SphereLight).range; + _vec4Array[2] = 0.0; + this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); - Vec3.toArray(_vec4Array, light.color); - if (light.useColorTemperature) { - const tempRGB = light.colorTemperatureRGB; - _vec4Array[0] *= tempRGB.x; - _vec4Array[1] *= tempRGB.y; - _vec4Array[2] *= tempRGB.z; - } - if (this._isHDR) { - _vec4Array[3] = sphereLit.luminance * this._fpScale * this._lightMeterScale; - } else { - _vec4Array[3] = sphereLit.luminance * exposure * this._lightMeterScale; - } - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); + Vec3.toArray(_vec4Array, light.color); + if (light.useColorTemperature) { + const tempRGB = light.colorTemperatureRGB; + _vec4Array[0] *= tempRGB.x; + _vec4Array[1] *= tempRGB.y; + _vec4Array[2] *= tempRGB.z; + } + if (this._isHDR) { + _vec4Array[3] = (light as SphereLight).luminance * this._fpScale * this._lightMeterScale; + } else { + _vec4Array[3] = (light as SphereLight).luminance * exposure * this._lightMeterScale; + } + this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); break; - case LightType.SPOT: - const spotLit = light as SpotLight; + case LightType.SPOT: + Vec3.toArray(_vec4Array, (light as SpotLight).position); + _vec4Array[3] = 1; + this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); - Vec3.toArray(_vec4Array, spotLit.position); - _vec4Array[3] = 1; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET); + _vec4Array[0] = (light as SpotLight).size; + _vec4Array[1] = (light as SpotLight).range; + _vec4Array[2] = (light as SpotLight).spotAngle; + this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); - _vec4Array[0] = spotLit.size; - _vec4Array[1] = spotLit.range; - _vec4Array[2] = spotLit.spotAngle; - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); + Vec3.toArray(_vec4Array, (light as SpotLight).direction); + this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET); - Vec3.toArray(_vec4Array, spotLit.direction); - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET); - - Vec3.toArray(_vec4Array, light.color); - if (light.useColorTemperature) { - const tempRGB = light.colorTemperatureRGB; - _vec4Array[0] *= tempRGB.x; - _vec4Array[1] *= tempRGB.y; - _vec4Array[2] *= tempRGB.z; - } - if (this._isHDR) { - _vec4Array[3] = spotLit.luminance * this._fpScale * this._lightMeterScale; - } else { - _vec4Array[3] = spotLit.luminance * exposure * this._lightMeterScale; - } - this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); + Vec3.toArray(_vec4Array, light.color); + if (light.useColorTemperature) { + const tempRGB = light.colorTemperatureRGB; + _vec4Array[0] *= tempRGB.x; + _vec4Array[1] *= tempRGB.y; + _vec4Array[2] *= tempRGB.z; + } + if (this._isHDR) { + _vec4Array[3] = (light as SpotLight).luminance * this._fpScale * this._lightMeterScale; + } else { + _vec4Array[3] = (light as SpotLight).luminance * exposure * this._lightMeterScale; + } + this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET); break; + default: } } diff --git a/cocos/core/platform/debug.ts b/cocos/core/platform/debug.ts index eeab4bfd16..afc74b4002 100644 --- a/cocos/core/platform/debug.ts +++ b/cocos/core/platform/debug.ts @@ -201,7 +201,7 @@ export function _resetDebugSetting (mode: DebugMode) { if (!condition) { const errorText = formatString(message, ...optionalParams); if (DEV) { - // tslint:disable:no-debugger + debugger; } else { @@ -231,7 +231,7 @@ export function _resetDebugSetting (mode: DebugMode) { } else if (mode === DebugMode.INFO) { if (JSB) { - // @ts-ignore + // @ts-expect-error if (scriptEngineType === 'JavaScriptCore') { // console.log has to use `console` as its context for iOS 8~9. Therefore, apply it. ccLog = (message?: any, ...optionalParams: any[]) => { diff --git a/cocos/core/platform/event-manager/event-manager.ts b/cocos/core/platform/event-manager/event-manager.ts index 0514a984b9..81c8f157c0 100644 --- a/cocos/core/platform/event-manager/event-manager.ts +++ b/cocos/core/platform/event-manager/event-manager.ts @@ -29,7 +29,7 @@ * @hidden */ -// tslint:disable:max-line-length + import { Event } from '../../event'; import { EventTouch } from './events'; @@ -41,13 +41,13 @@ import { errorID, warnID, logID, assertID } from '../../platform/debug'; const ListenerID = EventListener.ListenerID; function checkUINode (node) { - if(node && node.getComponent('cc.UITransform')) { + if (node && node.getComponent('cc.UITransform')) { return true; } return false; } -// tslint:disable-next-line: class-name + class _EventListenerVector { public gt0Index = 0; private _fixedListeners: EventListener[] = []; @@ -615,7 +615,7 @@ class EventManager { private _setDirtyForNode (node: Node) { // Mark the node dirty only when there is an event listener associated with it. - // @ts-ignore + // @ts-expect-error const selListeners = this._nodeListenersMap[node._id]; if (selListeners !== undefined) { for (let j = 0, len = selListeners.length; j < len; j++) { @@ -674,7 +674,7 @@ class EventManager { private _updateDirtyFlagForSceneGraph () { const locDirtyListeners = this._dirtyListeners; - // tslint:disable-next-line: forin + for (const selKey in locDirtyListeners) { this._setDirty(selKey, DIRTY_SCENE_GRAPH_PRIORITY); } @@ -779,8 +779,8 @@ class EventManager { } let p1 = node1, p2 = node2, ex = false; - let trans1 = node1._uiProps.uiTransformComp; - let trans2 = node2._uiProps.uiTransformComp; + const trans1 = node1._uiProps.uiTransformComp; + const trans2 = node2._uiProps.uiTransformComp; if (trans1.visibility !== trans2.visibility) { return trans2.visibility - trans1.visibility; } @@ -953,7 +953,7 @@ class EventManager { // const EventTouch = cc.Event.EventTouch; if (getCode === EventTouch.BEGAN) { if (!macro.ENABLE_MULTI_TOUCH && eventManager._currentTouch) { - const node = eventManager._currentTouchListener!._node; + const node = eventManager._currentTouchListener._node; if (!node || node.activeInHierarchy) { return false; } @@ -1171,7 +1171,7 @@ class EventManager { for (let i = listeners.length - 1; i >= 0; i--) { const selListener = listeners[i]; - // @ts-ignore + // @ts-expect-error if (selListener._onCustomEvent === callback || selListener.onEvent === callback) { selListener._setRegistered(false); if (selListener._getSceneGraphPriority() != null) { diff --git a/cocos/core/platform/event-manager/events.ts b/cocos/core/platform/event-manager/events.ts index c4d56aa4dc..3272443236 100644 --- a/cocos/core/platform/event-manager/events.ts +++ b/cocos/core/platform/event-manager/events.ts @@ -682,17 +682,17 @@ export class EventKeyboard extends Event { } // TODO -// @ts-ignore +// @ts-expect-error Event.EventMouse = EventMouse; // TODO -// @ts-ignore +// @ts-expect-error Event.EventTouch = EventTouch; // TODO -// @ts-ignore +// @ts-expect-error Event.EventAcceleration = EventAcceleration; // TODO -// @ts-ignore +// @ts-expect-error Event.EventKeyboard = EventKeyboard; diff --git a/cocos/core/platform/event-manager/input-manager.ts b/cocos/core/platform/event-manager/input-manager.ts index f03d0af819..51aa6cb212 100644 --- a/cocos/core/platform/event-manager/input-manager.ts +++ b/cocos/core/platform/event-manager/input-manager.ts @@ -382,9 +382,9 @@ class InputManager { this._glView = legacyCC.view; - let prohibition = sys.isMobile; - let supportMouse = ('mouse' in sys.capabilities); - let supportTouches = ('touches' in sys.capabilities); + const prohibition = sys.isMobile; + const supportMouse = ('mouse' in sys.capabilities); + const supportTouches = ('touches' in sys.capabilities); // Register mouse events. if (supportMouse) { @@ -428,7 +428,7 @@ class InputManager { } if (JSB || RUNTIME_BASED) { - // @ts-ignore + // @ts-expect-error jsb.device.setMotionEnabled(isEnable); } } @@ -445,7 +445,6 @@ class InputManager { let z = 0; // TODO - // @ts-ignore if (this._accelDeviceEvent === window.DeviceMotionEvent) { const deviceMotionEvent = eventData as DeviceMotionEvent; const eventAcceleration = deviceMotionEvent.accelerationIncludingGravity; @@ -509,9 +508,9 @@ class InputManager { this._accelInterval = interval; if (JSB || RUNTIME_BASED) { - // @ts-ignore + // @ts-expect-error if (jsb.device && jsb.device.setMotionInterval) { - // @ts-ignore + // @ts-expect-error jsb.device.setMotionInterval(interval); } } @@ -571,8 +570,8 @@ class InputManager { private _registerPointerLockEvent () { const lockChangeAlert = () => { const canvas = legacyCC.game.canvas; - // @ts-ignore - if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas){ + // @ts-expect-error + if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas) { this._pointLocked = true; } else { @@ -582,7 +581,7 @@ class InputManager { if ('onpointerlockchange' in document) { document.addEventListener('pointerlockchange', lockChangeAlert, false); } else if ('onmozpointerlockchange' in document) { - // @ts-ignore + // @ts-expect-error document.addEventListener('mozpointerlockchange', lockChangeAlert, false); } } @@ -658,14 +657,14 @@ class InputManager { }); } - // @ts-ignore + // @ts-expect-error listenDOMMouseEvent('mousewheel', EventMouse.SCROLL, (event, mouseEvent, location, pos) => { - // @ts-ignore + // @ts-expect-error mouseEvent.setScrollData(0, event.wheelDelta); }); /* firefox fix */ - // @ts-ignore + // @ts-expect-error listenDOMMouseEvent('DOMMouseScroll', EventMouse.SCROLL, (event, mouseEvent, location, pos) => { mouseEvent.setScrollData(0, event.detail * -120); }); @@ -678,10 +677,10 @@ class InputManager { MSPointerUp : this.handleTouchesEnd, MSPointerCancel : this.handleTouchesCancel, }; - // tslint:disable-next-line: forin + for (const eventName in _pointerEventsMap) { const touchEvent = _pointerEventsMap[eventName]; - // @ts-ignore + // @ts-expect-error element.addEventListener(eventName as MSPointerEventNames, (event: MSPointerEvent) => { const pos = this.getHTMLElementPosition(element); pos.left -= document.documentElement.scrollLeft; @@ -743,22 +742,21 @@ class InputManager { private _registerAccelerometerEvent () { this._acceleration = new Acceleration(); // TODO - // @ts-ignore + // @ts-expect-error this._accelDeviceEvent = window.DeviceMotionEvent || window.DeviceOrientationEvent; // TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. if (legacyCC.sys.browserType === legacyCC.sys.BROWSER_TYPE_MOBILE_QQ) { // TODO - // @ts-ignore + // @ts-expect-error this._accelDeviceEvent = window.DeviceOrientationEvent; } const _deviceEventType = // TODO - // @ts-ignore this._accelDeviceEvent === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation'; - // @ts-ignore + // @ts-expect-error _didAccelerateFun = (...args: any[]) => this.didAccelerate(...args); window.addEventListener(_deviceEventType, _didAccelerateFun, false); } @@ -766,7 +764,6 @@ class InputManager { private _unregisterAccelerometerEvent () { const _deviceEventType = // TODO - // @ts-ignore this._accelDeviceEvent === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation'; if (_didAccelerateFun) { window.removeEventListener(_deviceEventType, _didAccelerateFun, false); diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index 37e4f37dec..a7632f8955 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -33,9 +33,6 @@ import { EDITOR, TEST, COCOSPLAY, JSB, MINIGAME, HUAWEI, OPPO, VIVO, RUNTIME_BAS import { legacyCC } from '../global-exports'; import { warnID, log, logID } from './debug'; -// tslint:disable - -// @ts-ignore const _global = typeof window === 'undefined' ? global : window; enum NetworkType { @@ -61,7 +58,7 @@ enum NetworkType { * @zh 一系列系统相关环境变量 * @main */ -export const sys: { [x: string]: any; } = { +export const sys: Record = { /** * @en * Network type enumeration @@ -762,7 +759,7 @@ export const sys: { [x: string]: any; } = { */ openURL (url) { if (JSB || RUNTIME_BASED) { - // @ts-ignore + // @ts-expect-error jsb.openURL(url); } else { @@ -801,9 +798,9 @@ export const sys: { [x: string]: any; } = { * @return {Rect} */ getSafeAreaRect () { - let visibleSize = legacyCC.view.getVisibleSize(); + const visibleSize = legacyCC.view.getVisibleSize(); return legacyCC.rect(0, 0, visibleSize.width, visibleSize.height); - } + }, }; // ============= Platform Adaptation ============== @@ -821,7 +818,7 @@ if (_global.__globalAdapter && _global.__globalAdapter.adaptSys) { // darwin: sys.OS_OSX, // win32: sys.OS_WINDOWS, // linux: sys.OS_LINUX, -// // @ts-ignore +// // @ts-expect-error // })[process.platform] || sys.OS_UNKNOWN; // sys.browserType = sys.BROWSER_TYPE_UNKNOWN; // sys.browserVersion = ''; @@ -843,7 +840,7 @@ else if (JSB || RUNTIME_BASED) { platform = sys.COCOSPLAY; } else { - // @ts-ignore + // @ts-expect-error platform = __getPlatform(); } sys.platform = platform; @@ -859,14 +856,14 @@ else if (JSB || RUNTIME_BASED) { platform === sys.HUAWEI_QUICK_GAME || platform === sys.COCOSPLAY); - // @ts-ignore + // @ts-expect-error sys.os = __getOS(); - // @ts-ignore + // @ts-expect-error sys.language = __getCurrentLanguage(); - // @ts-ignore - let languageCode = JSB && __getCurrentLanguageCode(); + // @ts-expect-error + const languageCode = JSB && __getCurrentLanguageCode(); sys.languageCode = languageCode ? languageCode.toLowerCase() : 'unknown'; - // @ts-ignore + // @ts-expect-error sys.osVersion = __getOSVersion(); sys.osMainVersion = parseInt(sys.osVersion); sys.browserType = sys.BROWSER_TYPE_UNKNOWN; @@ -928,7 +925,7 @@ else { let currLanguage = nav.language; sys.languageCode = currLanguage.toLowerCase(); - // @ts-ignore + // @ts-expect-error currLanguage = currLanguage ? currLanguage : nav.browserLanguage; currLanguage = currLanguage ? currLanguage.split('-')[0] : sys.LANGUAGE_ENGLISH; sys.language = currLanguage; @@ -977,19 +974,19 @@ else { const typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i; const typeReg2 = /qq|qqbrowser|ucbrowser|ubrowser|edge/i; const typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i; - let browserTypes = typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua); + const browserTypes = typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua); let browserType = browserTypes ? browserTypes[0].toLowerCase() : sys.BROWSER_TYPE_UNKNOWN; - if(COCOSPLAY) { + if (COCOSPLAY) { browserType = sys.BROWSER_TYPE_COCOSPLAY; } - else if(HUAWEI) { + else if (HUAWEI) { browserType = sys.BROWSER_TYPE_HUAWEI_GAME; } - else if(OPPO) { + else if (OPPO) { browserType = sys.BROWSER_TYPE_OPPO_GAME; } - else if(VIVO) { + else if (VIVO) { browserType = sys.BROWSER_TYPE_VIVO_GAME; } else if (browserType === 'safari' && isAndroid) { @@ -998,7 +995,7 @@ else { else if (browserType === 'qq' && ua.match(/android.*applewebkit/i)) { browserType = sys.BROWSER_TYPE_ANDROID; } - let typeMap = { + const typeMap = { 'micromessenger': sys.BROWSER_TYPE_WECHAT, 'trident': sys.BROWSER_TYPE_IE, 'edge': sys.BROWSER_TYPE_EDGE, @@ -1091,7 +1088,6 @@ else { if (docEle.onkeyup !== undefined) { capabilities.keyboard = true; } - // @ts-ignore if (win.DeviceMotionEvent || win.DeviceOrientationEvent) { capabilities.accelerometer = true; } @@ -1142,7 +1138,6 @@ else { Object.defineProperty(__audioSupport, 'context', { get () { if (this._context) { return this._context; } - // @ts-ignore return this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, }); @@ -1152,7 +1147,7 @@ else { logID(5201); } - let formatSupport: string[] = []; + const formatSupport: string[] = []; (function () { const audio = document.createElement('audio'); if (audio.canPlayType) { @@ -1179,7 +1174,7 @@ else { const video = document.createElement('video'); if (video.canPlayType) { const canPlayTypes = ['mp4', 'webm']; - let format = sys.__videoSupport.format; + const format = sys.__videoSupport.format; canPlayTypes.forEach((type) => { if (video.canPlayType(`video/${type}`)) { format.push(`.${type}`); diff --git a/cocos/core/platform/view.ts b/cocos/core/platform/view.ts index 5df74ffa38..03a7214674 100644 --- a/cocos/core/platform/view.ts +++ b/cocos/core/platform/view.ts @@ -434,8 +434,8 @@ export class View extends EventTarget { * @zh 返回视图窗口可见区域像素尺寸。 */ public getVisibleSizeInPixel (): Size { - return new Size( this._visibleRect.width * this._scaleX, - this._visibleRect.height * this._scaleY ); + return new Size(this._visibleRect.width * this._scaleX, + this._visibleRect.height * this._scaleY); } /** @@ -495,7 +495,7 @@ export class View extends EventTarget { } } - // tslint:disable: max-line-length + /** * @en Sets the resolution policy with designed view size in points.
* The resolution policy include:
@@ -512,7 +512,7 @@ export class View extends EventTarget { */ public setDesignResolutionSize (width: number, height: number, resolutionPolicy: ResolutionPolicy|number) { // Defensive code - if ( !(width > 0 && height > 0) ){ + if (!(width > 0 && height > 0)) { errorID(2200); return; } @@ -545,12 +545,12 @@ export class View extends EventTarget { const result = policy.apply(this, this._designResolutionSize); - if (result.scale && result.scale.length === 2){ + if (result.scale && result.scale.length === 2) { this._scaleX = result.scale[0]; this._scaleY = result.scale[1]; } - if (result.viewport){ + if (result.viewport) { const vp = this._viewportRect; const vb = this._visibleRect; const rv = result.viewport; @@ -670,7 +670,7 @@ export class View extends EventTarget { result.x = x; result.y = y; } - if(legacyCC.GAME_VIEW) { + if (legacyCC.GAME_VIEW) { result.x /= legacyCC.gameView.canvas.width / legacyCC.game.canvas.width; result.y /= legacyCC.gameView.canvas.height / legacyCC.game.canvas.height; } @@ -739,7 +739,7 @@ export class View extends EventTarget { const locFrameSize = this._frameSize; const w = __BrowserGetter.availWidth(legacyCC.game.frame); const h = __BrowserGetter.availHeight(legacyCC.game.frame); - const isLandscape: Boolean = w >= h; + const isLandscape: boolean = w >= h; if (EDITOR || !legacyCC.sys.isMobile || (isLandscape && this._orientation & legacyCC.macro.ORIENTATION_LANDSCAPE) || @@ -831,16 +831,16 @@ export class View extends EventTarget { } } - private _convertMouseToLocation (in_out_point, relatedPos){ + private _convertMouseToLocation (in_out_point, relatedPos) { in_out_point.x = this._devicePixelRatio * (in_out_point.x - relatedPos.left); in_out_point.y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y); - if(legacyCC.GAME_VIEW) { + if (legacyCC.GAME_VIEW) { in_out_point.x /= legacyCC.gameView.canvas.width / legacyCC.game.canvas.width; in_out_point.y /= legacyCC.gameView.canvas.height / legacyCC.game.canvas.height; } } - private _convertTouchWidthScale (selTouch){ + private _convertTouchWidthScale (selTouch) { const viewport = this._viewportRect; const scaleX = this._scaleX; const scaleY = this._scaleY; @@ -857,7 +857,7 @@ export class View extends EventTarget { const scaleY = this._scaleY; let selPoint; let selPrePoint; - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < touches.length; i++) { const selTouch = touches[i]; selPoint = selTouch._point; @@ -884,7 +884,7 @@ interface AdaptResult { viewport?: null | Rect; } -/** +/** * ContainerStrategy class is the root strategy class of container's scale strategy, * it controls the behavior of how to scale the cc.game.container and cc.game.canvas object */ @@ -892,7 +892,7 @@ class ContainerStrategy { public static EQUAL_TO_FRAME: any; public static PROPORTION_TO_FRAME: any; - public name: string = 'ContainerStrategy'; + public name = 'ContainerStrategy'; /** * @en Manipulation before appling the strategy @@ -1018,10 +1018,10 @@ class ContentStrategy { public _buildResult (containerW, containerH, contentW, contentH, scaleX, scaleY): AdaptResult { // Makes content fit better the canvas - if ( Math.abs(containerW - contentW) < 2 ) { + if (Math.abs(containerW - contentW) < 2) { contentW = containerW; } - if ( Math.abs(containerH - contentH) < 2 ) { + if (Math.abs(containerH - contentH) < 2) { contentH = containerH; } @@ -1101,7 +1101,6 @@ class ContentStrategy { } // need to adapt prototype before instantiating - // @ts-ignore const _global = typeof window === 'undefined' ? global : window; const globalAdapter = _global.__globalAdapter; if (globalAdapter) { @@ -1221,35 +1220,35 @@ export class ResolutionPolicy { * The entire application is visible in the specified area without trying to preserve the original aspect ratio.
* Distortion can occur, and the application may appear stretched or compressed. */ - public static EXACT_FIT: number = 0; + public static EXACT_FIT = 0; /** * The entire application fills the specified area, without distortion but possibly with some cropping,
* while maintaining the original aspect ratio of the application. */ - public static NO_BORDER: number = 1; + public static NO_BORDER = 1; /** * The entire application is visible in the specified area without distortion while maintaining the original
* aspect ratio of the application. Borders can appear on two sides of the application. */ - public static SHOW_ALL: number = 2; + public static SHOW_ALL = 2; /** * The application takes the height of the design resolution size and modifies the width of the internal
* canvas so that it fits the aspect ratio of the device
* no distortion will occur however you must make sure your application works on different
* aspect ratios */ - public static FIXED_HEIGHT: number = 3; + public static FIXED_HEIGHT = 3; /** * The application takes the width of the design resolution size and modifies the height of the internal
* canvas so that it fits the aspect ratio of the device
* no distortion will occur however you must make sure your application works on different
* aspect ratios */ - public static FIXED_WIDTH: number = 4; + public static FIXED_WIDTH = 4; /** * Unknown policy */ - public static UNKNOWN: number = 5; + public static UNKNOWN = 5; public static ContainerStrategy: typeof ContainerStrategy = ContainerStrategy; public static ContentStrategy: typeof ContentStrategy = ContentStrategy; diff --git a/cocos/core/renderer/core/material-instance.ts b/cocos/core/renderer/core/material-instance.ts index 74974e27bf..270791a509 100644 --- a/cocos/core/renderer/core/material-instance.ts +++ b/cocos/core/renderer/core/material-instance.ts @@ -104,7 +104,7 @@ export class MaterialInstance extends Material { public onPassStateChange (dontNotify: boolean) { this._hash = Material.getHash(this); if (!dontNotify && this._owner) { - // @ts-ignore + // @ts-expect-error calling protected method here this._owner._onRebuildPSO(this._subModelIdx, this); } } diff --git a/cocos/core/renderer/core/memory-pools.ts b/cocos/core/renderer/core/memory-pools.ts index 1f1b506bc8..e6a3e4808d 100644 --- a/cocos/core/renderer/core/memory-pools.ts +++ b/cocos/core/renderer/core/memory-pools.ts @@ -29,15 +29,19 @@ */ import { DEBUG, JSB } from 'internal:constants'; +import { Layers } from 'cocos/core'; import { NativeBufferPool, NativeObjectPool, NativeBufferAllocator } from './native-pools'; -import { DescriptorSetInfo, +import { + DescriptorSetInfo, Device, DescriptorSet, ShaderInfo, Shader, InputAssemblerInfo, InputAssembler, PipelineLayoutInfo, PipelineLayout, Framebuffer, FramebufferInfo, PrimitiveMode, - DynamicStateFlags, ClearFlag, Color as GFXColor } from '../../gfx'; + DynamicStateFlags, ClearFlag, Color as GFXColor, +} from '../../gfx'; import { RenderPassStage } from '../../pipeline/define'; import { BatchingSchemes } from './pass'; -import { Layers } from '../../scene-graph/layers'; -import { Vec2, Vec3, Quat, Color, Rect, Mat4, IVec2Like, IVec3Like, IVec4Like, IMat4Like } from '../../math'; +import { + Vec2, Vec3, Quat, Color, Rect, Mat4, IVec2Like, IVec3Like, IVec4Like, IMat4Like, +} from '../../math'; import { plane } from '../../geometry'; interface IMemoryPool

{ @@ -58,33 +62,43 @@ enum BufferDataType { NEVER, } -type BufferManifest = { [key: string]: number | string; COUNT: number; }; +type BufferManifest = { [key: string]: number | string; COUNT: number }; type StandardBufferElement = number | IHandle; type GeneralBufferElement = StandardBufferElement | IVec2Like | IVec3Like | IVec4Like | IMat4Like; type BufferTypeManifest = { [key in E[keyof E]]: GeneralBufferElement }; type BufferDataTypeManifest = { [key in E[keyof E]]: BufferDataType }; class BufferPool

> implements IMemoryPool

{ - // naming convension: // this._bufferViews[chunk][entry][element] private _dataType: BufferDataTypeManifest; + private _elementCount: number; + private _entryBits: number; private _stride: number; + private _entriesPerChunk: number; + private _entryMask: number; + private _chunkMask: number; + private _poolFlag: number; private _arrayBuffers: ArrayBuffer[] = []; + private _freelists: number[][] = []; + private _uint32BufferViews: Uint32Array[][] = []; + private _float32BufferViews: Float32Array[][] = []; - private _hasUint32: boolean = false; - private _hasFloat32: boolean = false; + + private _hasUint32 = false; + + private _hasFloat32 = false; private _nativePool: NativeBufferPool; @@ -110,7 +124,7 @@ class BufferPool

; // guarantees the handle is always not zero } @@ -166,8 +180,8 @@ class BufferPool

> 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 || this._freelists[chunk].find((n) => n === entry))) { + if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length + || entry < 0 || entry >= this._entriesPerChunk || this._freelists[chunk].find((n) => n === entry))) { console.warn('invalid buffer pool handle'); return 0 as Extract; } @@ -178,8 +192,8 @@ class BufferPool

> 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 || this._freelists[chunk].find((n) => n === entry))) { + if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length + || entry < 0 || entry >= this._entriesPerChunk || this._freelists[chunk].find((n) => n === entry))) { console.warn('invalid buffer pool handle'); return; } @@ -188,13 +202,13 @@ class BufferPool

(handle: IHandle

, element: K, vec2: Extract) { // Web engine has Vec2 property, don't record it in shared memory. - if (!JSB) return; + if (!JSB) { return; } 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 || this._freelists[chunk].find((n) => n === entry))) { + if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length + || entry < 0 || entry >= this._entriesPerChunk || this._freelists[chunk].find((n) => n === entry))) { console.warn('invalid buffer pool handle'); return; } @@ -205,13 +219,13 @@ class BufferPool

(handle: IHandle

, element: K, vec3: Extract) { // Web engine has Vec3 property, don't record it in shared memory. - if (!JSB) return; + if (!JSB) { return; } 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 || this._freelists[chunk].find((n) => n === entry))) { + if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length + || entry < 0 || entry >= this._entriesPerChunk || this._freelists[chunk].find((n) => n === entry))) { console.warn('invalid buffer pool handle'); return; } @@ -222,31 +236,31 @@ class BufferPool

(handle: IHandle

, element: K, vec4: Extract) { // Web engine has Vec4 property, don't record it in shared memory. - if (!JSB) return; + if (!JSB) { return; } 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 || this._freelists[chunk].find((n) => n === entry))) { + if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length + || entry < 0 || entry >= this._entriesPerChunk || this._freelists[chunk].find((n) => n === entry))) { console.warn('invalid buffer pool handle'); return; } let index = element as unknown as number; const view = bufferViews[chunk][entry]; view[index++] = vec4.x; view[index++] = vec4.y; - view[index++] = vec4.z; view[index] = vec4.w; + view[index++] = vec4.z; view[index] = vec4.w; } public setMat4 (handle: IHandle

, element: K, mat4: Extract) { // Web engine has mat4 property, don't record it in shared memory. - if (!JSB) return; + if (!JSB) { return; } 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 || this._freelists[chunk].find((n) => n === entry))) { + if (DEBUG && (!handle || chunk < 0 || chunk >= bufferViews.length + || entry < 0 || entry >= this._entriesPerChunk || this._freelists[chunk].find((n) => n === entry))) { console.warn('invalid buffer pool handle'); return; } @@ -255,14 +269,14 @@ class BufferPool

) { 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 || this._freelists[chunk].find((n) => n === entry))) { + if (DEBUG && (!handle || chunk < 0 || chunk >= this._freelists.length + || entry < 0 || entry >= this._entriesPerChunk || this._freelists[chunk].find((n) => n === entry))) { console.warn('invalid buffer pool handle'); return; } @@ -273,13 +287,16 @@ class BufferPool

implements IMemoryPool

{ - private _ctor: (args: A, obj?: T) => T; + private _dtor?: (obj: T) => T | undefined; + private _indexMask: number; + private _poolFlag: number; private _array: (T | undefined)[] = []; + private _freelist: number[] = []; private _nativePool: NativeObjectPool; @@ -317,7 +334,7 @@ export class ObjectPool implements IMemo return this._array[index] as R; } - public free (handle: IHandle

) { + public free (handle: IHandle

): void { const index = this._indexMask & handle as unknown as number; if (DEBUG && (!handle || index < 0 || index >= this._array.length || this._freelist.find((n) => n === index))) { console.warn('invalid object pool handle'); @@ -329,11 +346,14 @@ export class ObjectPool implements IMemo } class BufferAllocator

implements IMemoryPool

{ - protected _nativeBufferAllocator: NativeBufferAllocator; + protected _buffers = new Map(); - protected _nextBufferIdx: number = 0; + + protected _nextBufferIdx = 0; + protected _poolFlag: number; + protected _bufferIdxMask: number; constructor (poolType: P) { @@ -352,7 +372,7 @@ class BufferAllocator

implements IMemoryPool

{ public free (handle: IHandle

) { const bufferIdx = this._bufferIdxMask & handle as unknown as number; if (!this._buffers.get(bufferIdx)) { - if (DEBUG) console.warn('invalid buffer allocator handle'); + if (DEBUG) { console.warn('invalid buffer allocator handle'); } return; } this._nativeBufferAllocator.free(bufferIdx); @@ -363,7 +383,7 @@ class BufferAllocator

implements IMemoryPool

{ const bufferIdx = this._bufferIdxMask & handle as unknown as number; const buffer = this._buffers.get(bufferIdx); if (!buffer) { - if (DEBUG) console.warn('invalid array pool index or invalid array handle'); + if (DEBUG) { console.warn('invalid array pool index or invalid array handle'); } return null!; } return buffer; @@ -372,10 +392,12 @@ class BufferAllocator

implements IMemoryPool

{ class TypedArrayPool

extends BufferAllocator

implements IMemoryPool

{ - declare protected _buffers: Map>; + protected _viewCtor: T; + protected _size: number; + protected _step: number; constructor (poolType: P, viewCtor: T, size: number, step?: number) { @@ -395,19 +417,19 @@ class TypedArrayPool

): never { return null!; } - public assign (handle: IHandle

, index: number, value: D) { + public assign (handle: IHandle

, targetIdx: number, value: D) { const bufferIdx = this._bufferIdxMask & handle as unknown as number; let array = this._buffers.get(bufferIdx); if (!array) { - if (DEBUG) console.warn('invalid array pool handle'); + if (DEBUG) { console.warn('invalid array pool handle'); } return; } // First element is the length of array. - index = index + 1; + const index = targetIdx + 1; if (index >= array.length) { let newSize = array.length; - while (index >= newSize) newSize += this._step; + while (index >= newSize) { newSize += this._step; } newSize *= this._viewCtor.BYTES_PER_ELEMENT; const newArray = new this._viewCtor(this._nativeBufferAllocator.alloc(bufferIdx, newSize)) as InstanceType; newArray.set(array); array = newArray; @@ -424,7 +446,7 @@ class TypedArrayPool

= array[0]) { - if (DEBUG) console.warn('invalid array pool index or invalid array handle'); + if (DEBUG) { console.warn('invalid array pool index or invalid array handle'); } return; } for (let i = index + 1; i < array[0]; ++i) { @@ -437,7 +459,7 @@ class TypedArrayPool

) { const bufferIdx = this._bufferIdxMask & handle as unknown as number; const array = this._buffers.get(bufferIdx); if (!array) { - if (DEBUG) console.warn('invalid array pool handle'); + if (DEBUG) { console.warn('invalid array pool handle'); } return; } array[0] = 0; @@ -473,7 +491,7 @@ class TypedArrayPool

= array[0]) { - if (DEBUG) console.warn('invalid array pool handle'); + if (DEBUG) { console.warn('invalid array pool handle'); } return 0 as D; } return array[index + 1] as D; @@ -483,7 +501,7 @@ class TypedArrayPool

> arrayPool: TypedArrayPool, elementPool: IMemoryPool, freeArrayItself = true, -) { +): void { const count = arrayPool.length(arrayHandle); for (let i = 0; i < count; i++) { const element = arrayPool.get(arrayHandle, i); - if (element) elementPool.free(element); + if (element) { elementPool.free(element); } } - if (freeArrayItself) arrayPool.free(arrayHandle); - else arrayPool.clear(arrayHandle); + if (freeArrayItself) { arrayPool.free(arrayHandle); } else { arrayPool.clear(arrayHandle); } } export enum PoolType { @@ -589,42 +606,45 @@ export type DepthStencilStateHandle = IHandle; export type BlendTargetHandle = IHandle; export type BlendStateHandle = IHandle; -// don't reuse any of these data-only structs, for GFX objects may directly reference them - // TODO: could use Labeled Tuple Element feature here after next babel update (required TS4.0+ support) export const ShaderPool = new ObjectPool(PoolType.SHADER, - (args: [Device, ShaderInfo], obj?: Shader) => obj ? (obj.initialize(args[1]), obj) : args[0].createShader(args[1]), - (obj: Shader) => (obj && obj.destroy(), obj), -); + (args: [Device, ShaderInfo], obj?: Shader) => (obj ? (obj.initialize(args[1]), obj) : args[0].createShader(args[1])), + (obj: Shader) => (obj && obj.destroy(), obj)); export const DSPool = new ObjectPool(PoolType.DESCRIPTOR_SETS, - (args: [Device, DescriptorSetInfo], obj?: DescriptorSet) => obj ? (obj.initialize(args[1]), obj) : args[0].createDescriptorSet(args[1]), - (obj: DescriptorSet) => (obj && obj.destroy(), obj), -); + (args: [Device, DescriptorSetInfo], obj?: DescriptorSet) => (obj ? (obj.initialize(args[1]), obj) : args[0].createDescriptorSet(args[1])), + (obj: DescriptorSet) => (obj && obj.destroy(), obj)); export const IAPool = new ObjectPool(PoolType.INPUT_ASSEMBLER, - (args: [Device, InputAssemblerInfo], obj?: InputAssembler) => obj ? (obj.initialize(args[1]), obj) : args[0].createInputAssembler(args[1]), - (obj: InputAssembler) => (obj && obj.destroy(), obj), -); + (args: [Device, InputAssemblerInfo], obj?: InputAssembler) => (obj ? (obj.initialize(args[1]), obj) : args[0].createInputAssembler(args[1])), + (obj: InputAssembler) => (obj && obj.destroy(), obj)); export const PipelineLayoutPool = new ObjectPool(PoolType.PIPELINE_LAYOUT, - (args: [Device, PipelineLayoutInfo], obj?: PipelineLayout) => obj ? (obj.initialize(args[1]), obj) : args[0].createPipelineLayout(args[1]), - (obj: PipelineLayout) => (obj && obj.destroy(), obj), -); + (args: [Device, PipelineLayoutInfo], obj?: PipelineLayout) => (obj ? (obj.initialize(args[1]), obj) : args[0].createPipelineLayout(args[1])), + (obj: PipelineLayout) => (obj && obj.destroy(), obj)); export const FramebufferPool = new ObjectPool(PoolType.FRAMEBUFFER, - (args: [Device, FramebufferInfo], obj?: Framebuffer) => obj ? (obj.initialize(args[1]), obj) : args[0].createFramebuffer(args[1]), - (obj: Framebuffer) => (obj && obj.destroy(), obj), -); + (args: [Device, FramebufferInfo], obj?: Framebuffer) => (obj ? (obj.initialize(args[1]), obj) : args[0].createFramebuffer(args[1])), + (obj: Framebuffer) => (obj && obj.destroy(), obj)); -export const SubModelArrayPool = new TypedArrayPool -(PoolType.SUB_MODEL_ARRAY, Uint32Array, 8, 4); -export const ModelArrayPool = new TypedArrayPool(PoolType.MODEL_ARRAY, Uint32Array, 32, 16); -export const AttributeArrayPool = new TypedArrayPool -(PoolType.ATTRIBUTE_ARRAY, Uint32Array, 8, 4); -export const FlatBufferArrayPool = new TypedArrayPool -(PoolType.FLAT_BUFFER_ARRAY, Uint32Array, 8, 4); -export const LightArrayPool = new TypedArrayPool(PoolType.LIGHT_ARRAY, Uint32Array, 8, 4); -export const BlendTargetArrayPool = new TypedArrayPool(PoolType.BLEND_TARGET_ARRAY, Uint32Array, 8, 4); +export const SubModelArrayPool = new TypedArrayPool( + PoolType.SUB_MODEL_ARRAY, Uint32Array, 8, 4, +); +export const ModelArrayPool = new TypedArrayPool( + PoolType.MODEL_ARRAY, Uint32Array, 32, 16, +); +export const AttributeArrayPool = new TypedArrayPool( + PoolType.ATTRIBUTE_ARRAY, Uint32Array, 8, 4, +); +export const FlatBufferArrayPool = new TypedArrayPool( + PoolType.FLAT_BUFFER_ARRAY, Uint32Array, 8, 4, +); +export const LightArrayPool = new TypedArrayPool( + PoolType.LIGHT_ARRAY, Uint32Array, 8, 4, +); +export const BlendTargetArrayPool = new TypedArrayPool( + PoolType.BLEND_TARGET_ARRAY, Uint32Array, 8, 4, +); export const RawBufferPool = new BufferAllocator(PoolType.RAW_BUFFER); -export const RawObjectPool = new ObjectPool(PoolType.RAW_OBJECT, (args: [Object?]) => args[0] || {}, (_: Object) => undefined); +export const RawObjectPool = new ObjectPool(PoolType.RAW_OBJECT, + (args: [Record?]) => args[0] || {}, (_: Record) => undefined); export enum PassView { PRIORITY, @@ -669,8 +689,8 @@ const passViewDataType: BufferDataTypeManifest = { [PassView.BLEND_STATE]: BufferDataType.UINT32, [PassView.DESCRIPTOR_SET]: BufferDataType.UINT32, [PassView.PIPELINE_LAYOUT]: BufferDataType.UINT32, - [PassView.COUNT]: BufferDataType.NEVER -} + [PassView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -723,12 +743,13 @@ const subModelViewDataType: BufferDataTypeManifest = { [SubModelView.INPUT_ASSEMBLER]: BufferDataType.UINT32, [SubModelView.SUB_MESH]: BufferDataType.UINT32, [SubModelView.COUNT]: BufferDataType.NEVER, -} +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const SubModelPool = new BufferPool - (PoolType.SUB_MODEL, subModelViewDataType, SubModelView); +export const SubModelPool = new BufferPool( + PoolType.SUB_MODEL, subModelViewDataType, SubModelView, +); export enum ModelView { ENABLED, @@ -767,8 +788,8 @@ const modelViewDataType: BufferDataTypeManifest = { [ModelView.SUB_MODEL_ARRAY]: BufferDataType.UINT32, [ModelView.INSTANCED_BUFFER]: BufferDataType.UINT32, [ModelView.INSTANCED_ATTR_ARRAY]: BufferDataType.UINT32, - [ModelView.COUNT]: BufferDataType.NEVER -} + [ModelView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -787,8 +808,8 @@ interface IAABBViewType extends BufferTypeManifest { const aabbViewDataType: BufferDataTypeManifest = { [AABBView.CENTER]: BufferDataType.FLOAT32, [AABBView.HALF_EXTENSION]: BufferDataType.FLOAT32, - [AABBView.COUNT]: BufferDataType.NEVER -} + [AABBView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -813,8 +834,8 @@ const sceneViewDataType: BufferDataTypeManifest = { [SceneView.MODEL_ARRAY]: BufferDataType.UINT32, [SceneView.SPHERE_LIGHT_ARRAY]: BufferDataType.UINT32, [SceneView.SPOT_LIGHT_ARRAY]: BufferDataType.UINT32, - [SceneView.COUNT]: BufferDataType.NEVER -} + [SceneView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -881,8 +902,8 @@ const cameraViewDataType: BufferDataTypeManifest = { [CameraView.MAT_VIEW_PROJ_INV]: BufferDataType.FLOAT32, [CameraView.MAT_PROJ]: BufferDataType.FLOAT32, [CameraView.MAT_PROJ_INV]: BufferDataType.FLOAT32, - [CameraView.COUNT]: BufferDataType.NEVER -} + [CameraView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -913,9 +934,9 @@ const nodeViewDataType: BufferDataTypeManifest = { [NodeView.WORLD_POSITION]: BufferDataType.FLOAT32, [NodeView.WORLD_ROTATION]: BufferDataType.FLOAT32, [NodeView.WORLD_MATRIX]: BufferDataType.FLOAT32, - [NodeView.COUNT]: BufferDataType.NEVER -} -// @ts-ignore Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. + [NodeView.COUNT]: BufferDataType.NEVER, +}; +// @ts-expect-error Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. if (!JSB) { delete NodeView[NodeView.COUNT]; NodeView[NodeView.COUNT = NodeView.LAYER + 1] = 'COUNT'; } // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) @@ -935,8 +956,8 @@ interface IRootViewType extends BufferTypeManifest { const rootViewDataType: BufferDataTypeManifest = { [RootView.CUMULATIVE_TIME]: BufferDataType.FLOAT32, [RootView.FRAME_TIME]: BufferDataType.FLOAT32, - [RootView.COUNT]: BufferDataType.NEVER -} + [RootView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -958,13 +979,14 @@ const renderWindowDataType: BufferDataTypeManifest = { [RenderWindowView.HAS_ON_SCREEN_ATTACHMENTS]: BufferDataType.UINT32, [RenderWindowView.HAS_OFF_SCREEN_ATTACHMENTS]: BufferDataType.UINT32, [RenderWindowView.FRAMEBUFFER]: BufferDataType.UINT32, - [RenderWindowView.COUNT]: BufferDataType.NEVER -} + [RenderWindowView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const RenderWindowPool = new BufferPool - (PoolType.RENDER_WINDOW, renderWindowDataType, RenderWindowView, 2); +export const RenderWindowPool = new BufferPool( + PoolType.RENDER_WINDOW, renderWindowDataType, RenderWindowView, 2, +); export enum FrustumView { VERTICES, // Vec3[8] @@ -980,7 +1002,7 @@ const frustumViewDataType: BufferDataTypeManifest = { [FrustumView.VERTICES]: BufferDataType.FLOAT32, [FrustumView.PLANES]: BufferDataType.FLOAT32, [FrustumView.COUNT]: BufferDataType.NEVER, -} +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -1005,14 +1027,16 @@ const ambientViewDataType: BufferDataTypeManifest = { [AmbientView.ILLUM]: BufferDataType.FLOAT32, [AmbientView.SKY_COLOR]: BufferDataType.FLOAT32, [AmbientView.GROUND_ALBEDO]: BufferDataType.FLOAT32, - [AmbientView.COUNT]: BufferDataType.NEVER -} -// @ts-ignore Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. -if (!JSB) {delete AmbientView[AmbientView.COUNT]; AmbientView[AmbientView.COUNT = AmbientView.ILLUM + 1] = 'COUNT'; } + [AmbientView.COUNT]: BufferDataType.NEVER, +}; +// @ts-expect-error Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. +if (!JSB) { delete AmbientView[AmbientView.COUNT]; AmbientView[AmbientView.COUNT = AmbientView.ILLUM + 1] = 'COUNT'; } // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const AmbientPool = new BufferPool(PoolType.AMBIENT, ambientViewDataType, AmbientView, 1); +export const AmbientPool = new BufferPool( + PoolType.AMBIENT, ambientViewDataType, AmbientView, 1, +); export enum SkyboxView { ENABLE, @@ -1033,8 +1057,8 @@ const skyboxDataType: BufferDataTypeManifest = { [SkyboxView.IS_RGBE]: BufferDataType.UINT32, [SkyboxView.USE_IBL]: BufferDataType.UINT32, [SkyboxView.MODEL]: BufferDataType.UINT32, - [SkyboxView.COUNT]: BufferDataType.NEVER -} + [SkyboxView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -1074,10 +1098,10 @@ const fogViewDataType: BufferDataTypeManifest = { [FogView.TOP]: BufferDataType.FLOAT32, [FogView.RANGE]: BufferDataType.FLOAT32, [FogView.COLOR]: BufferDataType.FLOAT32, - [FogView.COUNT]: BufferDataType.NEVER -} -// @ts-ignore Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. -if (!JSB) {delete FogView[FogView.COUNT]; FogView[FogView.COUNT = FogView.RANGE + 1] = 'COUNT'; } + [FogView.COUNT]: BufferDataType.NEVER, +}; +// @ts-expect-error Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. +if (!JSB) { delete FogView[FogView.COUNT]; FogView[FogView.COUNT = FogView.RANGE + 1] = 'COUNT'; } // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -1141,14 +1165,16 @@ const shadowsViewDataType: BufferDataTypeManifest = { [ShadowsView.SIZE]: BufferDataType.FLOAT32, [ShadowsView.NORMAL]: BufferDataType.FLOAT32, [ShadowsView.MAT_LIGHT]: BufferDataType.FLOAT32, - [ShadowsView.COUNT]: BufferDataType.NEVER -} -// @ts-ignore Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. -if (!JSB) {delete ShadowsView[ShadowsView.COUNT]; ShadowsView[ShadowsView.COUNT = ShadowsView.AUTO_ADAPT + 1] = 'COUNT'; } + [ShadowsView.COUNT]: BufferDataType.NEVER, +}; +// @ts-expect-error Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. +if (!JSB) { delete ShadowsView[ShadowsView.COUNT]; ShadowsView[ShadowsView.COUNT = ShadowsView.AUTO_ADAPT + 1] = 'COUNT'; } // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const ShadowsPool = new BufferPool(PoolType.SHADOW, shadowsViewDataType, ShadowsView, 1); +export const ShadowsPool = new BufferPool( + PoolType.SHADOW, shadowsViewDataType, ShadowsView, 1, +); export enum LightView { USE_COLOR_TEMPERATURE, @@ -1169,13 +1195,13 @@ export enum LightView { interface ILightViewType extends BufferTypeManifest { [LightView.USE_COLOR_TEMPERATURE]: number; [LightView.ILLUMINANCE]: number; - [LightView.NODE]:NodeHandle; - [LightView.RANGE]:number; - [LightView.TYPE]:number; - [LightView.AABB]:AABBHandle; - [LightView.FRUSTUM]:FrustumHandle; - [LightView.SIZE]:number; - [LightView.SPOT_ANGLE]:number; + [LightView.NODE]: NodeHandle; + [LightView.RANGE]: number; + [LightView.TYPE]: number; + [LightView.AABB]: AABBHandle; + [LightView.FRUSTUM]: FrustumHandle; + [LightView.SIZE]: number; + [LightView.SPOT_ANGLE]: number; [LightView.DIRECTION]: Vec3; [LightView.COLOR]: Vec3; [LightView.COLOR_TEMPERATURE_RGB]: Vec3; @@ -1196,8 +1222,8 @@ const lightViewDataType: BufferDataTypeManifest = { [LightView.COLOR]: BufferDataType.FLOAT32, [LightView.COLOR_TEMPERATURE_RGB]: BufferDataType.FLOAT32, [LightView.POSITION]: BufferDataType.FLOAT32, - [LightView.COUNT]: BufferDataType.NEVER -} + [LightView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. @@ -1216,10 +1242,10 @@ interface ISphereViewType extends BufferTypeManifest { const sphereViewDataType: BufferDataTypeManifest = { [SphereView.RADIUS]: BufferDataType.FLOAT32, [SphereView.CENTER]: BufferDataType.FLOAT32, - [SphereView.COUNT]: BufferDataType.NEVER -} -// @ts-ignore Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. -if (!JSB) {delete SphereView[SphereView.COUNT]; SphereView[SphereView.COUNT = SphereView.RADIUS + 1] = 'COUNT'; } + [SphereView.COUNT]: BufferDataType.NEVER, +}; +// @ts-expect-error Don't alloc memory for Vec3, Quat, Mat4 on web, as they are accessed by class member variable. +if (!JSB) { delete SphereView[SphereView.COUNT]; SphereView[SphereView.COUNT = SphereView.RADIUS + 1] = 'COUNT'; } export const SpherePool = new BufferPool(PoolType.SPHERE, sphereViewDataType, SphereView, 3); export enum FlatBufferView { @@ -1238,13 +1264,14 @@ const flatBufferViewDataType: BufferDataTypeManifest = { [FlatBufferView.STRIDE]: BufferDataType.UINT32, [FlatBufferView.AMOUNT]: BufferDataType.UINT32, [FlatBufferView.BUFFER]: BufferDataType.UINT32, - [FlatBufferView.COUNT]: BufferDataType.NEVER -} + [FlatBufferView.COUNT]: BufferDataType.NEVER, +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const FlatBufferPool = new BufferPool - (PoolType.FLAT_BUFFER, flatBufferViewDataType, FlatBufferView, 3); +export const FlatBufferPool = new BufferPool( + PoolType.FLAT_BUFFER, flatBufferViewDataType, FlatBufferView, 3, +); export enum SubMeshView { FLAT_BUFFER_ARRAY, // array handle @@ -1257,12 +1284,13 @@ interface ISubMeshViewType extends BufferTypeManifest { const subMeshViewDataType: BufferDataTypeManifest = { [SubMeshView.FLAT_BUFFER_ARRAY]: BufferDataType.UINT32, [SubMeshView.COUNT]: BufferDataType.NEVER, -} +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const SubMeshPool = new BufferPool - (PoolType.SUB_MESH, subMeshViewDataType, SubMeshView, 3); +export const SubMeshPool = new BufferPool( + PoolType.SUB_MESH, subMeshViewDataType, SubMeshView, 3, +); export enum RasterizerStateView { IS_DISCARD, @@ -1280,19 +1308,19 @@ export enum RasterizerStateView { COUNT } interface IRasterizerStateViewType extends BufferTypeManifest { - [RasterizerStateView.IS_DISCARD]: number, - [RasterizerStateView.POLYGO_MODEL]: number, - [RasterizerStateView.SHADE_MODEL]: number, - [RasterizerStateView.CULL_MODE]: number, - [RasterizerStateView.IS_FRONT_FACE_CCW]: number, - [RasterizerStateView.DEPTH_BIAS_ENABLED]: number, - [RasterizerStateView.DEPTH_BIAS]: number, - [RasterizerStateView.DEPTH_BIAS_CLAMP]: number, - [RasterizerStateView.DEPTH_BIAS_SLOP]: number, - [RasterizerStateView.IS_DEPTH_CLIP]: number, - [RasterizerStateView.IS_MULTI_SAMPLE]: number, - [RasterizerStateView.LINE_WIDTH]: number, - [RasterizerStateView.COUNT]: never + [RasterizerStateView.IS_DISCARD]: number; + [RasterizerStateView.POLYGO_MODEL]: number; + [RasterizerStateView.SHADE_MODEL]: number; + [RasterizerStateView.CULL_MODE]: number; + [RasterizerStateView.IS_FRONT_FACE_CCW]: number; + [RasterizerStateView.DEPTH_BIAS_ENABLED]: number; + [RasterizerStateView.DEPTH_BIAS]: number; + [RasterizerStateView.DEPTH_BIAS_CLAMP]: number; + [RasterizerStateView.DEPTH_BIAS_SLOP]: number; + [RasterizerStateView.IS_DEPTH_CLIP]: number; + [RasterizerStateView.IS_MULTI_SAMPLE]: number; + [RasterizerStateView.LINE_WIDTH]: number; + [RasterizerStateView.COUNT]: never; } const rasterizerStateViewDataType: BufferDataTypeManifest = { [RasterizerStateView.IS_DISCARD]: BufferDataType.UINT32, @@ -1307,13 +1335,14 @@ const rasterizerStateViewDataType: BufferDataTypeManifest -(PoolType.RASTERIZER_STATE, rasterizerStateViewDataType, RasterizerStateView, 9); +export const RasterizerStatePool = new BufferPool( + PoolType.RASTERIZER_STATE, rasterizerStateViewDataType, RasterizerStateView, 9, +); export enum DepthStencilStateView { DEPTH_TEST, @@ -1338,26 +1367,26 @@ export enum DepthStencilStateView { COUNT, } interface IDepthStencilStateViewType extends BufferTypeManifest { - [DepthStencilStateView.DEPTH_TEST]: number, - [DepthStencilStateView.DEPTH_WRITE]: number, - [DepthStencilStateView.DEPTH_FUNC]: number, - [DepthStencilStateView.STENCIL_TEST_FRONT]: number, - [DepthStencilStateView.STENCIL_FUNC_FRONT]: number, - [DepthStencilStateView.STENCIL_READ_MASK_FRONT]: number, - [DepthStencilStateView.STENCIL_WRITE_MASK_FRONT]: number, - [DepthStencilStateView.STENCIL_FAIL_OP_FRONT]: number, - [DepthStencilStateView.STENCIL_Z_FAIL_OP_FRONT]: number, - [DepthStencilStateView.STENCIL_PASS_OP_FRONT]: number, - [DepthStencilStateView.STENCIL_REF_FRONT]: number, - [DepthStencilStateView.STENCIL_TEST_BACK]: number, - [DepthStencilStateView.STENCIL_FUNC_BACK]: number, - [DepthStencilStateView.STENCIL_READ_MADK_BACK]: number, - [DepthStencilStateView.STENCIL_WRITE_MASK_BACK]: number, - [DepthStencilStateView.STENCIL_FAIL_OP_BACK]: number, - [DepthStencilStateView.STENCIL_Z_FAIL_OP_BACK]: number, - [DepthStencilStateView.STENCIL_PASS_OP_BACK]: number, - [DepthStencilStateView.STENCIL_REF_BACK]: number, - [DepthStencilStateView.COUNT]: never, + [DepthStencilStateView.DEPTH_TEST]: number; + [DepthStencilStateView.DEPTH_WRITE]: number; + [DepthStencilStateView.DEPTH_FUNC]: number; + [DepthStencilStateView.STENCIL_TEST_FRONT]: number; + [DepthStencilStateView.STENCIL_FUNC_FRONT]: number; + [DepthStencilStateView.STENCIL_READ_MASK_FRONT]: number; + [DepthStencilStateView.STENCIL_WRITE_MASK_FRONT]: number; + [DepthStencilStateView.STENCIL_FAIL_OP_FRONT]: number; + [DepthStencilStateView.STENCIL_Z_FAIL_OP_FRONT]: number; + [DepthStencilStateView.STENCIL_PASS_OP_FRONT]: number; + [DepthStencilStateView.STENCIL_REF_FRONT]: number; + [DepthStencilStateView.STENCIL_TEST_BACK]: number; + [DepthStencilStateView.STENCIL_FUNC_BACK]: number; + [DepthStencilStateView.STENCIL_READ_MADK_BACK]: number; + [DepthStencilStateView.STENCIL_WRITE_MASK_BACK]: number; + [DepthStencilStateView.STENCIL_FAIL_OP_BACK]: number; + [DepthStencilStateView.STENCIL_Z_FAIL_OP_BACK]: number; + [DepthStencilStateView.STENCIL_PASS_OP_BACK]: number; + [DepthStencilStateView.STENCIL_REF_BACK]: number; + [DepthStencilStateView.COUNT]: never; } const depthStencilStateViewDataType: BufferDataTypeManifest = { [DepthStencilStateView.DEPTH_TEST]: BufferDataType.UINT32, @@ -1380,12 +1409,13 @@ const depthStencilStateViewDataType: BufferDataTypeManifest -(PoolType.DEPTH_STENCIL_STATE, depthStencilStateViewDataType, DepthStencilStateView, 9); +export const DepthStencilStatePool = new BufferPool( + PoolType.DEPTH_STENCIL_STATE, depthStencilStateViewDataType, DepthStencilStateView, 9, +); export enum BlendTargetView { BLEND, @@ -1399,15 +1429,15 @@ export enum BlendTargetView { COUNT, } interface IBlendTargetViewType extends BufferTypeManifest { - [BlendTargetView.BLEND]: number, - [BlendTargetView.BLEND_SRC]: number, - [BlendTargetView.BLEND_DST]: number, - [BlendTargetView.BLEND_EQ]: number, - [BlendTargetView.BLEND_SRC_ALPHA]: number, - [BlendTargetView.BLEND_DST_ALPHA]: number, - [BlendTargetView.BLEND_ALPHA_EQ]: number, - [BlendTargetView.BLEND_COLOR_MASK]: number, - [BlendTargetView.COUNT]: never, + [BlendTargetView.BLEND]: number; + [BlendTargetView.BLEND_SRC]: number; + [BlendTargetView.BLEND_DST]: number; + [BlendTargetView.BLEND_EQ]: number; + [BlendTargetView.BLEND_SRC_ALPHA]: number; + [BlendTargetView.BLEND_DST_ALPHA]: number; + [BlendTargetView.BLEND_ALPHA_EQ]: number; + [BlendTargetView.BLEND_COLOR_MASK]: number; + [BlendTargetView.COUNT]: never; } const blendTargetViewDataType: BufferDataTypeManifest = { [BlendTargetView.BLEND]: BufferDataType.UINT32, @@ -1419,12 +1449,13 @@ const blendTargetViewDataType: BufferDataTypeManifest = [BlendTargetView.BLEND_ALPHA_EQ]: BufferDataType.UINT32, [BlendTargetView.BLEND_COLOR_MASK]: BufferDataType.UINT32, [BlendTargetView.COUNT]: BufferDataType.NEVER, -} +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const BlendTargetPool = new BufferPool -(PoolType.BLEND_TARGET, depthStencilStateViewDataType, BlendTargetView, 9); +export const BlendTargetPool = new BufferPool( + PoolType.BLEND_TARGET, depthStencilStateViewDataType, BlendTargetView, 9, +); export enum BlendStateView { IS_A2C, @@ -1434,11 +1465,11 @@ export enum BlendStateView { COUNT = 7, } interface IBlendStateViewType extends BufferTypeManifest { - [BlendStateView.IS_A2C]: number, - [BlendStateView.IS_INDEPEND]: number, - [BlendStateView.BLEND_COLOR]: GFXColor, - [BlendStateView.BLEND_TARGET]: BlendTargetArrayHandle, - [BlendStateView.COUNT]: never, + [BlendStateView.IS_A2C]: number; + [BlendStateView.IS_INDEPEND]: number; + [BlendStateView.BLEND_COLOR]: GFXColor; + [BlendStateView.BLEND_TARGET]: BlendTargetArrayHandle; + [BlendStateView.COUNT]: never; } const blendStateViewDataType: BufferDataTypeManifest = { [BlendStateView.IS_A2C]: BufferDataType.UINT32, @@ -1446,9 +1477,10 @@ const blendStateViewDataType: BufferDataTypeManifest = { [BlendStateView.BLEND_COLOR]: BufferDataType.FLOAT32, [BlendStateView.BLEND_TARGET]: BufferDataType.UINT32, [BlendStateView.COUNT]: BufferDataType.NEVER, -} +}; // Theoretically we only have to declare the type view here while all the other arguments can be inferred. // but before the official support of Partial Type Argument Inference releases, (microsoft/TypeScript#26349) // we'll have to explicitly declare all these types. -export const BlendStatePool = new BufferPool -(PoolType.BLEND_STATE, blendStateViewDataType, BlendStateView, 9); \ No newline at end of file +export const BlendStatePool = new BufferPool( + PoolType.BLEND_STATE, blendStateViewDataType, BlendStateView, 9, +); diff --git a/cocos/core/renderer/core/pass-instance.ts b/cocos/core/renderer/core/pass-instance.ts index 44db229444..9e53014647 100644 --- a/cocos/core/renderer/core/pass-instance.ts +++ b/cocos/core/renderer/core/pass-instance.ts @@ -39,7 +39,6 @@ import { PassView, PassPool } from './memory-pools'; * @zh 表示 [[Pass]] 的一种特殊实例 */ export class PassInstance extends Pass { - /** * @en The parent pass * @zh 相关联的原始 Pass @@ -47,7 +46,9 @@ export class PassInstance extends Pass { get parent () { return this._parent; } private _parent: Pass; + private _owner: MaterialInstance; + private _dontNotify = false; constructor (parent: Pass, owner: MaterialInstance) { diff --git a/cocos/core/renderer/core/pass-utils.ts b/cocos/core/renderer/core/pass-utils.ts index ce6a55b155..52deb8a842 100644 --- a/cocos/core/renderer/core/pass-utils.ts +++ b/cocos/core/renderer/core/pass-utils.ts @@ -29,7 +29,7 @@ */ import { Type } from '../../gfx/define'; -import { Color, Mat3, Mat4, Vec2, Vec3, Vec4, Quat } from '../../math'; +import { Color, Mat3, Mat4, Vec2, Vec3, Vec4, Quat, IVec2Like, IVec3Like, IVec4Like, IMat3Like, IMat4Like } from '../../math'; const dtMask = 0xf0000000; // 4 bits => 16 property types const typeMask = 0x0fc00000; // 6 bits => 64 types @@ -52,14 +52,14 @@ export enum PropertyType { SAMPLER, } -export const genHandle = (pt: PropertyType, set: number, binding: number, type: Type, offset: number = 0) => +export const genHandle = (pt: PropertyType, set: number, binding: number, type: Type, offset = 0): number => ((pt << 28) & dtMask) | ((type << 22) & typeMask) | ((set << 20) & setMask) | ((binding << 14) & bindingMask) | (offset & offsetMask); -export const getPropertyTypeFromHandle = (handle: number) => (handle & dtMask) >>> 28; -export const getTypeFromHandle = (handle: number) => (handle & typeMask) >>> 22; -export const getSetIndexFromHandle = (handle: number) => (handle & setMask) >>> 20; -export const getBindingFromHandle = (handle: number) => (handle & bindingMask) >>> 14; -export const getOffsetFromHandle = (handle: number) => (handle & offsetMask); -export const customizeType = (handle: number, type: Type) => (handle & ~typeMask) | ((type << 22) & typeMask); +export const getPropertyTypeFromHandle = (handle: number): number => (handle & dtMask) >>> 28; +export const getTypeFromHandle = (handle: number): number => (handle & typeMask) >>> 22; +export const getSetIndexFromHandle = (handle: number): number => (handle & setMask) >>> 20; +export const getBindingFromHandle = (handle: number): number => (handle & bindingMask) >>> 14; +export const getOffsetFromHandle = (handle: number): number => (handle & offsetMask); +export const customizeType = (handle: number, type: Type): number => (handle & ~typeMask) | ((type << 22) & typeMask); /** * @en Vector type uniforms @@ -68,31 +68,31 @@ export const customizeType = (handle: number, type: Type) => (handle & ~typeMask export type MaterialProperty = number | Vec2 | Vec3 | Vec4 | Color | Mat3 | Mat4 | Quat; export const type2reader = { - [Type.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'), - [Type.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx], - [Type.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx), - [Type.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx), - [Type.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx), - [Type.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx], - [Type.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx), - [Type.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx), - [Type.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx), - [Type.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.fromArray(v, a, idx), - [Type.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.fromArray(v, a, idx), + [Type.UNKNOWN]: (a: Float32Array, v: number, idx = 0): void => console.warn('illegal uniform handle'), + [Type.INT]: (a: Float32Array, v: number, idx = 0): number => a[idx], + [Type.INT2]: (a: Float32Array, v: IVec2Like, idx = 0): IVec2Like => Vec2.fromArray(v, a, idx), + [Type.INT3]: (a: Float32Array, v: IVec3Like, idx = 0): IVec3Like => Vec3.fromArray(v, a, idx), + [Type.INT4]: (a: Float32Array, v: IVec4Like, idx = 0): IVec4Like => Vec4.fromArray(v, a, idx), + [Type.FLOAT]: (a: Float32Array, v: number, idx = 0): number => a[idx], + [Type.FLOAT2]: (a: Float32Array, v: IVec2Like, idx = 0): IVec2Like => Vec2.fromArray(v, a, idx), + [Type.FLOAT3]: (a: Float32Array, v: IVec3Like, idx = 0): IVec3Like => Vec3.fromArray(v, a, idx), + [Type.FLOAT4]: (a: Float32Array, v: IVec4Like, idx = 0): IVec4Like => Vec4.fromArray(v, a, idx), + [Type.MAT3]: (a: Float32Array, v: IMat3Like, idx = 0): IMat3Like => Mat3.fromArray(v, a, idx), + [Type.MAT4]: (a: Float32Array, v: IMat4Like, idx = 0): IMat4Like => Mat4.fromArray(v, a, idx), }; export const type2writer = { - [Type.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'), - [Type.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, - [Type.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx), - [Type.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx), - [Type.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx), - [Type.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, - [Type.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx), - [Type.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx), - [Type.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx), - [Type.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.toArray(a, v, idx), - [Type.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.toArray(a, v, idx), + [Type.UNKNOWN]: (a: Float32Array, v: number, idx = 0): void => console.warn('illegal uniform handle'), + [Type.INT]: (a: Float32Array, v: number, idx = 0): number => a[idx] = v, + [Type.INT2]: (a: Float32Array, v: IVec2Like, idx = 0): Float32Array => Vec2.toArray(a, v, idx), + [Type.INT3]: (a: Float32Array, v: IVec3Like, idx = 0): Float32Array => Vec3.toArray(a, v, idx), + [Type.INT4]: (a: Float32Array, v: IVec4Like, idx = 0): Float32Array => Vec4.toArray(a, v, idx), + [Type.FLOAT]: (a: Float32Array, v: number, idx = 0): number => a[idx] = v, + [Type.FLOAT2]: (a: Float32Array, v: IVec2Like, idx = 0): Float32Array => Vec2.toArray(a, v, idx), + [Type.FLOAT3]: (a: Float32Array, v: IVec3Like, idx = 0): Float32Array => Vec3.toArray(a, v, idx), + [Type.FLOAT4]: (a: Float32Array, v: IVec4Like, idx = 0): Float32Array => Vec4.toArray(a, v, idx), + [Type.MAT3]: (a: Float32Array, v: IMat3Like, idx = 0): Float32Array => Mat3.toArray(a, v, idx), + [Type.MAT4]: (a: Float32Array, v: IMat4Like, idx = 0): Float32Array => Mat4.toArray(a, v, idx), }; const defaultValues = [ @@ -107,7 +107,7 @@ const defaultValues = [ * @zh 根据指定的 Uniform 类型来获取默认值 * @param type The type of the uniform */ -export function getDefaultFromType (type: Type) { +export function getDefaultFromType (type: Type): readonly number[] | string { switch (type) { case Type.BOOL: case Type.INT: @@ -148,7 +148,7 @@ export type MacroRecord = Record; */ export function overrideMacros (target: MacroRecord, source: MacroRecord): boolean { const entries = Object.entries(source); - let isDifferent: boolean = false; + let isDifferent = false; for (let i = 0; i < entries.length; i++) { if (target[entries[i][0]] !== entries[i][1]) { target[entries[i][0]] = entries[i][1]; diff --git a/cocos/core/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts index 6531e4061c..bbf6c3428e 100644 --- a/cocos/core/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -29,24 +29,30 @@ */ import { EDITOR } from 'internal:constants'; -import { builtinResMgr } from '../../3d/builtin/init'; -import { IPassInfo, IPassStates, IPropertyInfo } from '../../assets/effect-asset'; -import { TextureBase } from '../../assets/texture-base'; -import { RenderPassStage, RenderPriority } from '../../pipeline/define'; -import { getPhaseID } from '../../pipeline/pass-phase'; -import { Root } from '../../root'; -import { murmurhash2_32_gc } from '../../utils/murmurhash2_gc'; -import { IProgramInfo, programLib } from './program-lib'; -import { samplerLib } from './sampler-lib'; -import { PassView, PassPool, DSPool, PassHandle, ShaderHandle, NULL_HANDLE } from './memory-pools'; -import { customizeType, getBindingFromHandle, getPropertyTypeFromHandle, getDefaultFromType, - getOffsetFromHandle, getTypeFromHandle, MacroRecord, MaterialProperty, type2reader, type2writer, PropertyType } from './pass-utils'; -import { BufferUsageBit, GetTypeSize, MemoryUsageBit, PrimitiveMode, - Type, DynamicStateFlagBit, Feature } from '../../gfx/define'; -import { DescriptorSetLayoutInfo, Texture, Device, Buffer, BufferInfo, BufferViewInfo, - Sampler, DescriptorSet, DescriptorSetInfo } from '../../gfx'; import { Color } from '../../gfx/define-class'; -import { BlendState, BlendTarget, DepthStencilState, RasterizerState } from '../../gfx'; +import { Root } from '../../root'; +import { TextureBase } from '../../assets/texture-base'; +import { builtinResMgr } from '../../3d/builtin/init'; +import { getPhaseID } from '../../pipeline/pass-phase'; +import { murmurhash2_32_gc } from '../../utils/murmurhash2_gc'; +import { samplerLib } from './sampler-lib'; +import { + BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet, + DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, +} from '../../gfx'; +import { + BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, +} from '../../gfx/define'; +import { + DSPool, NULL_HANDLE, PassHandle, PassPool, PassView, ShaderHandle, +} from './memory-pools'; +import { IPassInfo, IPassStates, IPropertyInfo } from '../../assets/effect-asset'; +import { IProgramInfo, programLib } from './program-lib'; +import { + MacroRecord, MaterialProperty, PropertyType, customizeType, + getBindingFromHandle, getDefaultFromType, getOffsetFromHandle, getPropertyTypeFromHandle, getTypeFromHandle, type2reader, type2writer, +} from './pass-utils'; +import { RenderPassStage, RenderPriority } from '../../pipeline/define'; export interface IPassInfoFull extends IPassInfo { // generated part @@ -63,8 +69,8 @@ export interface IMacroPatch { interface IPassDynamics { [type: number]: { - dirty: boolean, - value: number[], + dirty: boolean; + value: number; }; } @@ -74,16 +80,14 @@ const _bufferInfo = new BufferInfo( ); const _bufferViewInfo = new BufferViewInfo(null!); -const _dsLayoutInfo = new DescriptorSetLayoutInfo(); const _dsInfo = new DescriptorSetInfo(null!); export enum BatchingSchemes { INSTANCING = 1, VB_MERGING = 2, -}; +} -// tslint:disable: no-shadowed-variable export declare namespace Pass { export type getPropertyTypeFromHandle = typeof getPropertyTypeFromHandle; export type getTypeFromHandle = typeof getTypeFromHandle; @@ -93,7 +97,6 @@ export declare namespace Pass { export type getOffsetFromHandle = typeof getOffsetFromHandle; export type PropertyType = typeof PropertyType; } -// tslint:enable: no-shadowed-variable /** * @en Render pass, store actual resources for the rendering process @@ -124,12 +127,14 @@ export class Pass { */ public static getBindingFromHandle = getBindingFromHandle; + protected static getOffsetFromHandle = getOffsetFromHandle; + /** * @en Fill a pass represented by the given pass handle with the given override info * @param hPass The pass handle point to the pass * @param info The pass override info */ - public static fillPipelineInfo (pass: Pass, info: PassOverrides) { + public static fillPipelineInfo (pass: Pass, info: PassOverrides): void { const hPass = pass.handle; if (info.priority !== undefined) { PassPool.set(hPass, PassView.PRIORITY, info.priority); } if (info.primitive !== undefined) { PassPool.set(hPass, PassView.PRIMITIVE, info.primitive); } @@ -140,7 +145,7 @@ export class Pass { const bs = pass._bs; if (info.blendState) { const bsInfo = info.blendState; - const targets = bsInfo.targets; + const { targets } = bsInfo; if (targets) { targets.forEach((t, i) => { bs.setTarget(i, t as BlendTarget); @@ -161,9 +166,9 @@ export class Pass { * * @param hPass Handle of the pass info used to compute hash value. */ - public static getPassHash (pass: Pass, hShader: ShaderHandle) { + public static getPassHash (pass: Pass, hShader: ShaderHandle): number { const hPass = pass.handle; - let res = hShader + ',' + PassPool.get(hPass, PassView.PRIMITIVE) + ',' + PassPool.get(hPass, PassView.DYNAMIC_STATES); + let res = `${hShader as unknown as number},${PassPool.get(hPass, PassView.PRIMITIVE)},${PassPool.get(hPass, PassView.DYNAMIC_STATES)}`; res += serializeBlendState(pass._bs); res += serializeDepthStencilState(pass._dss); res += serializeRasterizerState(pass._rs); @@ -171,34 +176,51 @@ export class Pass { return murmurhash2_32_gc(res, 666); } - protected static getOffsetFromHandle = getOffsetFromHandle; - // internal resources protected _rootBuffer: Buffer | null = null; + protected _rootBufferDirty = false; + protected _buffers: Buffer[] = []; + protected _descriptorSet: DescriptorSet = null!; + // internal data protected _passIndex = 0; + protected _propertyIndex = 0; + protected _programName = ''; + protected _dynamics: IPassDynamics = {}; + protected _propertyHandleMap: Record = {}; + protected _rootBlock: ArrayBuffer | null = null; + protected _blocks: Float32Array[] = []; + protected _shaderInfo: IProgramInfo = null!; + protected _defines: MacroRecord = {}; + protected _properties: Record = {}; + // external references protected _root: Root; + protected _device: Device; + // native data protected _hShaderDefault: ShaderHandle = NULL_HANDLE; - protected _handle: PassHandle = NULL_HANDLE; - protected _bs: BlendState = new BlendState(); - protected _dss: DepthStencilState = new DepthStencilState(); - protected _rs: RasterizerState = new RasterizerState(); + protected _handle: PassHandle = NULL_HANDLE; + + protected _bs: BlendState = new BlendState(); + + protected _dss: DepthStencilState = new DepthStencilState(); + + protected _rs: RasterizerState = new RasterizerState(); constructor (root: Root) { this._root = root; @@ -209,7 +231,7 @@ export class Pass { * @en Initialize the pass with given pass info, shader will be compiled in the init process * @zh 根据指定参数初始化当前 pass,shader 会在这一阶段就尝试编译。 */ - public initialize (info: IPassInfoFull) { + public initialize (info: IPassInfoFull): void { this._doInit(info); this.resetUBOs(); this.resetTextures(); @@ -234,10 +256,13 @@ export class Pass { * pass.setUniform(hThreshold, 0.5); // now, albedoScale.w = 0.5 * ``` */ - public getHandle (name: string, offset = 0, targetType = Type.UNKNOWN) { + public getHandle (name: string, offset = 0, targetType = Type.UNKNOWN): number { let handle = this._propertyHandleMap[name]; if (!handle) { return 0; } - if (targetType) { handle = customizeType(handle, targetType); } - else if (offset) { handle = customizeType(handle, getTypeFromHandle(handle) - offset); } + if (targetType) { + handle = customizeType(handle, targetType); + } else if (offset) { + handle = customizeType(handle, getTypeFromHandle(handle) - offset); + } return handle + offset; } @@ -246,7 +271,7 @@ export class Pass { * @zh 获取指定 uniform 的 binding。 * @param name The name of target uniform */ - public getBinding (name: string) { + public getBinding (name: string): number { const handle = this.getHandle(name); if (!handle) { return -1; } return Pass.getBindingFromHandle(handle); @@ -258,7 +283,7 @@ export class Pass { * @param handle The handle for the target uniform * @param value New value */ - public setUniform (handle: number, value: MaterialProperty) { + public setUniform (handle: number, value: MaterialProperty): void { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); @@ -273,12 +298,12 @@ export class Pass { * @param handle The handle for the target uniform * @param out The output property to store the result */ - public getUniform (handle: number, out: MaterialProperty) { + public getUniform (handle: number, out: T): T { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); const block = this._blocks[binding]; - return type2reader[type](block, out, ofs); + return type2reader[type](block, out, ofs) as T; } /** @@ -287,7 +312,7 @@ export class Pass { * @param handle The handle for the target uniform * @param value New value */ - public setUniformArray (handle: number, value: MaterialProperty[]) { + public setUniformArray (handle: number, value: MaterialProperty[]): void { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const stride = GetTypeSize(type) >> 2; @@ -306,7 +331,7 @@ export class Pass { * @param binding The binding for target uniform of texture type * @param value Target texture */ - public bindTexture (binding: number, value: Texture, index?: number) { + public bindTexture (binding: number, value: Texture, index?: number): void { this._descriptorSet.bindTexture(binding, value, index || 0); } @@ -316,7 +341,7 @@ export class Pass { * @param binding The binding for target uniform of sampler type * @param value Target sampler */ - public bindSampler (binding: number, value: Sampler, index?: number) { + public bindSampler (binding: number, value: Sampler, index?: number): void { this._descriptorSet.bindSampler(binding, value, index || 0); } @@ -326,7 +351,7 @@ export class Pass { * @param state Target dynamic state * @param value Target value */ - public setDynamicState (state: DynamicStateFlagBit, value: any) { + public setDynamicState (state: DynamicStateFlagBit, value: number): void { const ds = this._dynamics[state]; if (ds && ds.value === value) { return; } ds.value = value; ds.dirty = true; @@ -338,7 +363,7 @@ export class Pass { * @param original The original pass info * @param value The override pipeline state info */ - public overridePipelineStates (original: IPassInfo, overrides: PassOverrides) { + public overridePipelineStates (original: IPassInfo, overrides: PassOverrides): void { console.warn('base pass cannot override states, please use pass instance instead.'); } @@ -346,7 +371,7 @@ export class Pass { * @en Update the current uniforms data. * @zh 更新当前 Uniform 数据。 */ - public update () { + public update (): void { if (this._rootBufferDirty && this._rootBuffer) { this._rootBuffer.update(this._rootBlock!); this._rootBufferDirty = false; @@ -358,7 +383,7 @@ export class Pass { * @en Destroy the current pass. * @zh 销毁当前 pass。 */ - public destroy () { + public destroy (): void { for (let i = 0; i < this._shaderInfo.blocks.length; i++) { const u = this._shaderInfo.blocks[i]; this._buffers[u.binding].destroy(); @@ -388,15 +413,15 @@ export class Pass { * This method does not support array type uniform. * @zh 重置指定(非数组) Uniform 为 [[EffectAsset]] 默认值。 */ - public resetUniform (name: string) { + public resetUniform (name: string): void { const handle = this.getHandle(name); - if (!handle) return; + if (!handle) { return; } const type = Pass.getTypeFromHandle(handle); const binding = Pass.getBindingFromHandle(handle); const ofs = Pass.getOffsetFromHandle(handle); const block = this._blocks[binding]; const info = this._properties[name]; - const value = info && info.value || getDefaultFromType(type); + const value = (info && info.value) || getDefaultFromType(type); type2writer[type](block, value, ofs); this._rootBufferDirty = true; } @@ -405,14 +430,14 @@ export class Pass { * @en Resets the value of the given texture by name to the default value in [[EffectAsset]]. * @zh 重置指定贴图为 [[EffectAsset]] 默认值。 */ - public resetTexture (name: string, index?: number) { + public resetTexture (name: string, index?: number): void { const handle = this.getHandle(name); - if (!handle) return; + if (!handle) { return; } const type = Pass.getTypeFromHandle(handle); const binding = Pass.getBindingFromHandle(handle); const info = this._properties[name]; const value = info && info.value; - const texName = value ? value + '-texture' : getDefaultFromType(type) as string; + const texName = value ? `${value as string}-texture` : getDefaultFromType(type) as string; const textureBase = builtinResMgr.get(texName); const texture = textureBase && textureBase.getGFXTexture()!; const samplerHash = info && (info.samplerHash !== undefined) ? info.samplerHash : textureBase && textureBase.getSamplerHash(); @@ -425,7 +450,7 @@ export class Pass { * @en Resets all uniform buffer objects to the default values in [[EffectAsset]] * @zh 重置所有 UBO 为默认值。 */ - public resetUBOs () { + public resetUBOs (): void { for (let i = 0; i < this._shaderInfo.blocks.length; i++) { const u = this._shaderInfo.blocks[i]; const block = this._blocks[u.binding]; @@ -434,7 +459,7 @@ export class Pass { const cur = u.members[j]; const info = this._properties[cur.name]; const givenDefault = info && info.value; - const value = (givenDefault ? givenDefault : getDefaultFromType(cur.type)) as number[]; + const value = (givenDefault || getDefaultFromType(cur.type)) as number[]; const size = (GetTypeSize(cur.type) >> 2) * cur.count; for (let k = 0; k + value.length <= size; k += value.length) { block.set(value, ofs + k); } ofs += size; @@ -447,7 +472,7 @@ export class Pass { * @en Resets all textures and samplers to the default values in [[EffectAsset]] * @zh 重置所有 texture 和 sampler 为初始默认值。 */ - public resetTextures () { + public resetTextures (): void { for (let i = 0; i < this._shaderInfo.samplers.length; i++) { const u = this._shaderInfo.samplers[i]; for (let j = 0; j < u.count; j++) { @@ -460,8 +485,8 @@ export class Pass { * @en Try to compile the shader and retrieve related resources references. * @zh 尝试编译 shader 并获取相关资源引用。 */ - public tryCompile () { - const pipeline = this._root.pipeline; + public tryCompile (): boolean { + const { pipeline } = this._root; if (!pipeline) { return false; } this._syncBatchingScheme(); this._hShaderDefault = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline); @@ -478,8 +503,8 @@ export class Pass { */ public getShaderVariant (patches: IMacroPatch[] | null = null): ShaderHandle { if (!this._hShaderDefault && !this.tryCompile()) { - console.warn(`pass resources incomplete`); - return NULL_HANDLE; + console.warn('pass resources incomplete'); + return NULL_HANDLE as ShaderHandle; } if (!patches) { @@ -490,12 +515,12 @@ export class Pass { for (let i = 0; i < patches.length; i++) { if (!patches[i].name.startsWith('CC_')) { console.warn('cannot patch non-builtin macros'); - return NULL_HANDLE; + return NULL_HANDLE as ShaderHandle; } } } - const pipeline = this._root.pipeline!; + const { pipeline } = this._root; for (let i = 0; i < patches.length; i++) { const patch = patches[i]; this._defines[patch.name] = patch.value; @@ -514,13 +539,14 @@ export class Pass { /** * @private */ - public beginChangeStatesSilently () {} + public beginChangeStatesSilently (): void {} + /** * @private */ - public endChangeStatesSilently () {} + public endChangeStatesSilently (): void {} - protected _doInit (info: IPassInfoFull, copyDefines = false) { + protected _doInit (info: IPassInfoFull, copyDefines = false): void { const handle = this._handle = PassPool.alloc(); PassPool.set(handle, PassView.PRIORITY, RenderPriority.DEFAULT); PassPool.set(handle, PassView.STAGE, RenderPassStage.DEFAULT); @@ -533,7 +559,7 @@ export class Pass { this._passIndex = info.passIndex; this._propertyIndex = info.propertyIndex !== undefined ? info.propertyIndex : info.passIndex; this._programName = info.program; - this._defines = copyDefines ? Object.assign({}, info.defines) : info.defines; + this._defines = copyDefines ? ({ ...info.defines }) : info.defines; this._shaderInfo = programLib.getTemplate(info.program); this._properties = info.properties || this._properties; // pipeline state @@ -568,7 +594,7 @@ export class Pass { } // create buffer views for (let i = 0, count = 0; i < blocks.length; i++) { - const binding = blocks[i].binding; + const { binding } = blocks[i]; const size = blockSizes[i]; _bufferViewInfo.buffer = this._rootBuffer!; _bufferViewInfo.offset = startOffsets[count++]; @@ -591,7 +617,7 @@ export class Pass { Object.assign(directHandleMap, indirectHandleMap); } - protected _syncBatchingScheme () { + protected _syncBatchingScheme (): void { if (this._defines.USE_INSTANCING) { if (this._device.hasFeature(Feature.INSTANCED_ARRAYS)) { PassPool.set(this._handle, PassView.BATCHING_SCHEME, BatchingSchemes.INSTANCING); @@ -607,37 +633,59 @@ export class Pass { } // infos - get root () { return this._root; } - get device () { return this._device; } - get shaderInfo () { return this._shaderInfo; } - get localSetLayout () { return programLib.getDescriptorSetLayout(this._device, this._programName, true); } - get program () { return this._programName; } - get properties () { return this._properties; } - get defines () { return this._defines; } - get passIndex () { return this._passIndex; } - get propertyIndex () { return this._propertyIndex; } - // data - get dynamics () { return this._dynamics; } - get blocks () { return this._blocks; } - // states - get handle () { return this._handle; } - get priority () { return PassPool.get(this._handle, PassView.PRIORITY); } - get primitive () { return PassPool.get(this._handle, PassView.PRIMITIVE); } - get stage () { return PassPool.get(this._handle, PassView.STAGE); } - get phase () { return PassPool.get(this._handle, PassView.PHASE); } - get rasterizerState () { return this._rs; } - get depthStencilState () { return this._dss; } - get blendState () { return this._bs; } - get dynamicStates () { return PassPool.get(this._handle, PassView.DYNAMIC_STATES); } - get batchingScheme () { return PassPool.get(this._handle, PassView.BATCHING_SCHEME); } - get descriptorSet () { return this._descriptorSet; } - get hash () { return PassPool.get(this._handle, PassView.HASH); } + get root (): Root { return this._root; } - get rootBufferDirty () { return this._rootBufferDirty; } + get device (): Device { return this._device; } + + get shaderInfo (): IProgramInfo { return this._shaderInfo; } + + get localSetLayout (): DescriptorSetLayout { return programLib.getDescriptorSetLayout(this._device, this._programName, true); } + + get program (): string { return this._programName; } + + get properties (): Record { return this._properties; } + + get defines (): Record { return this._defines; } + + get passIndex (): number { return this._passIndex; } + + get propertyIndex (): number { return this._propertyIndex; } + + // data + get dynamics (): IPassDynamics { return this._dynamics; } + + get blocks (): Float32Array[] { return this._blocks; } + + // states + get handle (): PassHandle { return this._handle; } + + get priority (): RenderPriority { return PassPool.get(this._handle, PassView.PRIORITY); } + + get primitive (): PrimitiveMode { return PassPool.get(this._handle, PassView.PRIMITIVE); } + + get stage (): RenderPassStage { return PassPool.get(this._handle, PassView.STAGE); } + + get phase (): number { return PassPool.get(this._handle, PassView.PHASE); } + + get rasterizerState (): RasterizerState { return this._rs; } + + get depthStencilState (): DepthStencilState { return this._dss; } + + get blendState (): BlendState { return this._bs; } + + get dynamicStates (): DynamicStateFlags { return PassPool.get(this._handle, PassView.DYNAMIC_STATES); } + + get batchingScheme (): BatchingSchemes { return PassPool.get(this._handle, PassView.BATCHING_SCHEME); } + + get descriptorSet (): DescriptorSet { return this._descriptorSet; } + + get hash (): number { return PassPool.get(this._handle, PassView.HASH); } + + get rootBufferDirty (): boolean { return this._rootBufferDirty; } } -function serializeBlendState (bs: BlendState) { - let res = `,bs,${bs.isA2C},${bs.blendColor}`; +function serializeBlendState (bs: BlendState): string { + let res = `,bs,${bs.isA2C}`; for (const t of bs.targets) { res += `,bt,${t.blend},${t.blendEq},${t.blendAlphaEq},${t.blendColorMask}`; res += `,${t.blendSrc},${t.blendDst},${t.blendSrcAlpha},${t.blendDstAlpha}`; @@ -645,11 +693,11 @@ function serializeBlendState (bs: BlendState) { return res; } -function serializeRasterizerState (rs: RasterizerState) { - return ',rs,' + rs.cullMode + ',' + rs.depthBias + ',' + rs.isFrontFaceCCW; +function serializeRasterizerState (rs: RasterizerState): string { + return `,rs,${rs.cullMode},${rs.depthBias},${rs.isFrontFaceCCW}`; } -function serializeDepthStencilState (dss: DepthStencilState) { +function serializeDepthStencilState (dss: DepthStencilState): string { let res = `,dss,${dss.depthTest},${dss.depthWrite},${dss.depthFunc}`; res += `,${dss.stencilTestFront},${dss.stencilFuncFront},${dss.stencilRefFront},${dss.stencilReadMaskFront}`; res += `,${dss.stencilFailOpFront},${dss.stencilZFailOpFront},${dss.stencilPassOpFront},${dss.stencilWriteMaskFront}`; @@ -657,4 +705,3 @@ function serializeDepthStencilState (dss: DepthStencilState) { res += `,${dss.stencilFailOpBack},${dss.stencilZFailOpBack},${dss.stencilPassOpBack},${dss.stencilWriteMaskBack}`; return res; } - diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index b28da83e63..474db8bced 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -73,9 +73,9 @@ function getBitCount (cnt: number) { function mapDefine (info: IDefineInfo, def: number | string | boolean) { switch (info.type) { - case 'boolean': return (typeof def === 'number' ? def : (def ? 1 : 0)) + ''; + case 'boolean': return typeof def === 'number' ? def.toString() : (def ? '1' : '0'); case 'string': return def !== undefined ? def as string : info.options![0]; - case 'number': return (def !== undefined ? def as number : info.range![0]) + ''; + case 'number': return def !== undefined ? def.toString() : info.range![0].toString(); } console.warn(`unknown define type '${info.type}'`); return '-1'; // should neven happen @@ -310,9 +310,9 @@ class ProgramLib { } const mapped = tmplDef._map(value); const offset = tmplDef._offset; - key += offset + (mapped + '|'); + key += `${offset}${mapped}|`; } - return key + tmpl.hash; + return `${key}${tmpl.hash}`; } else { let key = 0; for (let i = 0; i < tmplDefs.length; i++) { @@ -339,7 +339,7 @@ class ProgramLib { const regexes = names.map((cur) => { let val = defines[cur]; if (typeof val === 'boolean') { val = val ? '1' : '0'; } - return new RegExp(cur + val); + return new RegExp(`${cur}${val}`); }); const keys = Object.keys(this._cache).filter((k) => regexes.every((re) => re.test(ShaderPool.get(this._cache[k]).name))); for (let i = 0; i < keys.length; i++) { diff --git a/cocos/core/renderer/core/render-window.ts b/cocos/core/renderer/core/render-window.ts index de3d8692b5..fe328a2a93 100644 --- a/cocos/core/renderer/core/render-window.ts +++ b/cocos/core/renderer/core/render-window.ts @@ -77,11 +77,11 @@ export class RenderWindow { root._createWindowFun = (_root: Root): RenderWindow => new RenderWindow(_root); } - protected _title: string = ''; - protected _width: number = 1; - protected _height: number = 1; - protected _nativeWidth: number = 1; - protected _nativeHeight: number = 1; + protected _title = ''; + protected _width = 1; + protected _height = 1; + protected _nativeWidth = 1; + protected _nativeHeight = 1; protected _renderPass: RenderPass | null = null; protected _colorTextures: (Texture | null)[] = []; protected _depthStencilTexture: Texture | null = null; diff --git a/cocos/core/renderer/core/texture-buffer-pool.ts b/cocos/core/renderer/core/texture-buffer-pool.ts index b45b300f5d..2b7de1e36a 100644 --- a/cocos/core/renderer/core/texture-buffer-pool.ts +++ b/cocos/core/renderer/core/texture-buffer-pool.ts @@ -142,7 +142,7 @@ export class TextureBufferPool { public createChunk (length: number) { const texSize = length * length * this._formatSize; - console.info('TextureBufferPool: Allocate chunk ' + this._chunkCount + ', size: ' + texSize + ', format: ' + this._format); + console.info(`TextureBufferPool: Allocate chunk ${this._chunkCount}, size: ${texSize}, format: ${this._format}`); const texture: Texture = this._device.createTexture(new TextureInfo( TextureType.TEX2D, diff --git a/cocos/core/renderer/models/baked-skinning-model.ts b/cocos/core/renderer/models/baked-skinning-model.ts index bb8212cb66..d7d83f54a8 100644 --- a/cocos/core/renderer/models/baked-skinning-model.ts +++ b/cocos/core/renderer/models/baked-skinning-model.ts @@ -121,7 +121,7 @@ export class BakedSkinningModel extends MorphModel { const worldBounds = this._worldBounds; if (worldBounds && skelBound) { const node = this.transform; - // @ts-ignore TS2339 + // @ts-expect-error TS2339 skelBound.transform(node._mat, node._pos, node._rot, node._scale, worldBounds); AABBPool.setVec3(this._hWorldBounds, AABBView.CENTER, worldBounds.center); AABBPool.setVec3(this._hWorldBounds, AABBView.HALF_EXTENSION, worldBounds.halfExtents); diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index eda6cb80d9..28fe24d811 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -35,7 +35,9 @@ import { getWorldTransformUntilRoot } from '../../animation/transform-utils'; import { Mesh } from '../../assets/mesh'; import { Skeleton } from '../../assets/skeleton'; import { aabb } from '../../geometry'; -import { Address, BufferUsageBit, Filter, Format, FormatInfos, MemoryUsageBit, Feature } from '../../gfx/define'; +import { + Address, BufferUsageBit, Filter, Format, FormatInfos, MemoryUsageBit, Feature, +} from '../../gfx/define'; import { Device, Buffer, BufferInfo } from '../../gfx'; import { Mat4, Quat, Vec3 } from '../../math'; import { UBOSkinningAnimation } from '../../pipeline/define'; @@ -50,9 +52,8 @@ export const MINIMUM_JOINT_TEXTURE_SIZE = EDITOR ? 2040 : 480; // have to be mul export function selectJointsMediumFormat (device: Device): Format { if (device.hasFeature(Feature.TEXTURE_FLOAT)) { return Format.RGBA32F; - } else { - return Format.RGBA8; } + return Format.RGBA8; } // Linear Blending Skinning @@ -81,8 +82,7 @@ const v3_2 = new Vec3(); function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) { Mat4.toRTS(mat, qt_1, v3_1, v3_2); // sign consistency - if (firstBone) { Quat.copy(dq_0, qt_1); } - else if (Quat.dot(dq_0, qt_1) < 0) { Quat.multiplyScalar(qt_1, qt_1, -1); } + if (firstBone) { Quat.copy(dq_0, qt_1); } else if (Quat.dot(dq_0, qt_1) < 0) { Quat.multiplyScalar(qt_1, qt_1, -1); } // conversion Quat.set(dq_1, v3_1.x, v3_1.y, v3_1.z, 0); Quat.multiplyScalar(dq_1, Quat.multiply(dq_1, dq_1, qt_1), 0.5); @@ -154,14 +154,18 @@ export interface ICustomJointTextureLayout { const Inf = Number.MAX_SAFE_INTEGER; export class JointTexturePool { - private _device: Device; + private _pool: TextureBufferPool; + private _textureBuffers = new Map(); // per skeleton per clip + private _formatSize: number; + private _pixelsPerJoint: number; private _customPool: TextureBufferPool; + private _chunkIdxMap = new Map(); // hash -> chunkIdx get pixelsPerJoint () { @@ -190,7 +194,7 @@ export class JointTexturePool { const chunkIdx = this._customPool.createChunk(layout.textureLength); for (let j = 0; j < layout.contents.length; j++) { const content = layout.contents[j]; - const skeleton = content.skeleton; + const { skeleton } = content; this._chunkIdxMap.set(skeleton, chunkIdx); // include default pose too for (let k = 0; k < content.clips.length; k++) { const clip = content.clips[k]; @@ -216,12 +220,19 @@ export class JointTexturePool { if (!texture) { const bufSize = jointCount * 12; const customChunkIdx = this._chunkIdxMap.get(hash); - const handle = customChunkIdx !== undefined ? - this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : - this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT); + const handle = customChunkIdx !== undefined + ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) + : this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT); if (!handle) { return texture; } - texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, bounds: new Map(), - skeletonHash: skeleton.hash, clipHash: 0, readyToBeDeleted: false, handle }; + texture = { + pixelOffset: handle.start / this._formatSize, + refCount: 1, + bounds: new Map(), + skeletonHash: skeleton.hash, + clipHash: 0, + readyToBeDeleted: false, + handle, + }; textureBuffer = new Float32Array(bufSize); buildTexture = true; } else { texture.refCount++; } Vec3.set(v3_min, Inf, Inf, Inf); @@ -263,19 +274,27 @@ export class JointTexturePool { if (texture && texture.bounds.has(mesh.hash)) { texture.refCount++; return texture; } const { joints, bindposes } = skeleton; const clipData = SkelAnimDataHub.getOrExtract(clip); - const frames = clipData.info.frames; + const { frames } = clipData.info; let textureBuffer: Float32Array = null!; let buildTexture = false; const jointCount = joints.length; if (!texture) { const bufSize = jointCount * 12 * frames; const customChunkIdx = this._chunkIdxMap.get(hash); - const handle = customChunkIdx !== undefined ? - this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : - this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT); + const handle = customChunkIdx !== undefined + ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) + : this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT); if (!handle) { return null; } const animInfos = this._createAnimInfos(skeleton, clip, skinningRoot); - texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, bounds: new Map(), - skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle, animInfos }; + texture = { + pixelOffset: handle.start / this._formatSize, + refCount: 1, + bounds: new Map(), + skeletonHash: skeleton.hash, + clipHash: clip.hash, + readyToBeDeleted: false, + handle, + animInfos, + }; textureBuffer = new Float32Array(bufSize); buildTexture = true; } else { texture.refCount++; } const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton); @@ -286,7 +305,9 @@ export class JointTexturePool { for (let f = 0, offset = 0; f < frames; f++) { const bound = bounds[f]; for (let j = 0; j < jointCount; j++, offset += 12) { - const { curveData, downstream, bindposeIdx, bindposeCorrection } = texture.animInfos![j]; + const { + curveData, downstream, bindposeIdx, bindposeCorrection, + } = texture.animInfos![j]; let mat: Mat4; let transformValid = true; if (curveData && downstream) { // curve & static two-way combination mat = Mat4.multiply(m4_1, curveData[f], downstream); @@ -427,7 +448,9 @@ export class JointTexturePool { } } } - animInfos.push({ curveData: source && source.worldMatrix.values as Mat4[], downstream, bindposeIdx, bindposeCorrection }); + animInfos.push({ + curveData: source && source.worldMatrix.values as Mat4[], downstream, bindposeIdx, bindposeCorrection, + }); } return animInfos; } @@ -441,6 +464,7 @@ export interface IAnimInfo { export class JointAnimationInfo { private _pool = new Map(); // per node + private _device: Device; constructor (device: Device) { diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index 9c94faa1f2..f4d2e5415d 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -199,7 +199,7 @@ export class SkinningModel extends MorphModel { public updateTransform (stamp: number) { const root = this.transform!; - // @ts-ignore TS2445 + // @ts-expect-error TS2445 if (root.hasChangedFlags || root._dirtyFlags) { root.updateWorldTransform(); this._transformUpdated = true; @@ -217,7 +217,7 @@ export class SkinningModel extends MorphModel { } if (this._modelBounds && this._worldBounds) { aabb.fromPoints(this._modelBounds, v3_min, v3_max); - // @ts-ignore TS2445 + // @ts-expect-error TS2445 this._modelBounds.transform(root._mat, root._pos, root._rot, root._scale, this._worldBounds); } } diff --git a/cocos/core/renderer/scene/light.ts b/cocos/core/renderer/scene/light.ts index 329aea11d1..a26d3982d3 100644 --- a/cocos/core/renderer/scene/light.ts +++ b/cocos/core/renderer/scene/light.ts @@ -2,7 +2,9 @@ import { Vec3 } from '../../math'; import { TransformBit } from '../../scene-graph/node-enum'; import { RenderScene } from './render-scene'; import { Node } from '../../scene-graph'; -import { LightHandle, NULL_HANDLE, LightPool, LightView } from '../core/memory-pools'; +import { + LightHandle, NULL_HANDLE, LightPool, LightView, +} from '../core/memory-pools'; // Color temperature (in Kelvin) to RGB export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { @@ -14,16 +16,16 @@ export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { // Approximate Planckian locus in CIE 1960 UCS const kSqr = kelvin * kelvin; - const u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / ( 1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr); - const v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / ( 1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr); + const u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / (1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr); + const v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / (1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr); const d = (2.0 * u - 8.0 * v + 4.0); - const x = 3.0 * u / d; - const y = 2.0 * v / d; - const z = 1.0 - x - y; + const x = (3.0 * u) / d; + const y = (2.0 * v) / d; + const z = (1.0 - x) - y; - const X = 1.0 / y * x; - const Z = 1.0 / y * z; + const X = (1.0 / y) * x; + const Z = (1.0 / y) * z; // XYZ to RGB with BT.709 primaries rgb.x = 3.2404542 * X + -1.5371385 + -0.4985314 * Z; @@ -41,7 +43,6 @@ export enum LightType { export const nt2lm = (size: number) => 4 * Math.PI * Math.PI * size * size; export class Light { - set color (color: Vec3) { this._color.set(color); LightPool.setVec3(this._handle, LightView.COLOR, color); @@ -56,7 +57,7 @@ export class Light { } get useColorTemperature (): boolean { - return LightPool.get(this._handle, LightView.USE_COLOR_TEMPERATURE) === 1 ? true : false; + return LightPool.get(this._handle, LightView.USE_COLOR_TEMPERATURE) === 1; } set colorTemperature (val: number) { @@ -106,11 +107,17 @@ export class Light { } protected _color: Vec3 = new Vec3(1, 1, 1); - protected _colorTemp: number = 6550.0; + + protected _colorTemp = 6550.0; + protected _colorTempRGB: Vec3 = new Vec3(1, 1, 1); + protected _scene: RenderScene | null = null; + protected _node: Node | null = null; + protected _name: string | null = null; + protected _handle: LightHandle = NULL_HANDLE; public initialize () { diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 11f6c88007..a1d95d985b 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -256,13 +256,13 @@ export class Model { public updateTransform (stamp: number) { const node = this.transform; - // @ts-ignore TS2445 + // @ts-expect-error TS2445 if (node.hasChangedFlags || node._dirtyFlags) { node.updateWorldTransform(); this._transformUpdated = true; const worldBounds = this._worldBounds; if (this._modelBounds && worldBounds) { - // @ts-ignore TS2445 + // @ts-expect-error TS2445 this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, worldBounds); AABBPool.setVec3(this._hWorldBounds, AABBView.CENTER, worldBounds.center); AABBPool.setVec3(this._hWorldBounds, AABBView.HALF_EXTENSION, worldBounds.halfExtents); @@ -280,7 +280,7 @@ export class Model { if (!this._transformUpdated) { return; } this._transformUpdated = false; - // @ts-ignore + // @ts-expect-error const worldMatrix = this.transform._mat; const idx = this._instMatWorldIdx; if (idx >= 0) { diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index 488ca4ffe4..1c39db1e52 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -105,7 +105,7 @@ export class Skybox { if (!this._model) { this._model = new legacyCC.renderer.scene.Model() as Model; - // @ts-ignore skybox don't need local buffers + // @ts-expect-error skybox don't need local buffers this._model._initLocalDescriptors = () => {}; } diff --git a/cocos/core/renderer/scene/spot-light.ts b/cocos/core/renderer/scene/spot-light.ts index 49a28f2d9c..f414771587 100644 --- a/cocos/core/renderer/scene/spot-light.ts +++ b/cocos/core/renderer/scene/spot-light.ts @@ -1,7 +1,9 @@ import { aabb, frustum } from '../../geometry'; import { Mat4, Quat, Vec3 } from '../../math'; import { Light, LightType, nt2lm } from './light'; -import { AABBHandle, AABBPool, AABBView, FrustumHandle, FrustumPool, LightPool, LightView, NULL_HANDLE } from '../core/memory-pools'; +import { + AABBHandle, AABBPool, AABBView, FrustumHandle, FrustumPool, LightPool, LightView, NULL_HANDLE, +} from '../core/memory-pools'; import { recordFrustumToSharedMemory } from '../../geometry/frustum'; const _forward = new Vec3(0, 0, -1); @@ -13,15 +15,23 @@ const _matViewProjInv = new Mat4(); export class SpotLight extends Light { protected _dir: Vec3 = new Vec3(1.0, -1.0, -1.0); - protected _size: number = 0.15; - protected _range: number = 5.0; + + protected _range = 5.0; + protected _spotAngle: number = Math.cos(Math.PI / 6); + protected _pos: Vec3; + protected _aabb: aabb; + protected _frustum: frustum; - protected _angle: number = 0; + + protected _angle = 0; + protected _needUpdate = false; + protected _hAABB: AABBHandle = NULL_HANDLE; + protected _hFrustum: FrustumHandle = NULL_HANDLE; get position () { @@ -37,6 +47,7 @@ export class SpotLight extends Light { } set range (range: number) { + this._range = range; LightPool.set(this._handle, LightView.RANGE, range); this._needUpdate = true; } @@ -63,7 +74,7 @@ export class SpotLight extends Light { set spotAngle (val: number) { this._angle = val; - LightPool.set(this._handle, LightView.SPOT_ANGLE, Math.cos(val * 0.5)) + LightPool.set(this._handle, LightView.SPOT_ANGLE, Math.cos(val * 0.5)); this._needUpdate = true; } diff --git a/cocos/core/renderer/scene/submodel.ts b/cocos/core/renderer/scene/submodel.ts index 387a83aa7c..35309ed4ff 100644 --- a/cocos/core/renderer/scene/submodel.ts +++ b/cocos/core/renderer/scene/submodel.ts @@ -1,7 +1,7 @@ import { RenderingSubMesh } from '../../assets/mesh'; import { RenderPriority } from '../../pipeline/define'; import { BatchingSchemes, IMacroPatch, Pass } from '../core/pass'; -import { DSPool, IAPool, SubModelPool, SubModelView, SubModelHandle, NULL_HANDLE, SubMeshPool } from '../core/memory-pools'; +import { DSPool, IAPool, SubModelPool, SubModelView, SubModelHandle, NULL_HANDLE } from '../core/memory-pools'; import { DescriptorSet, DescriptorSetInfo, Device, InputAssembler } from '../../gfx'; import { legacyCC } from '../../global-exports'; @@ -31,7 +31,7 @@ export class SubModel { } } - get passes () { + get passes (): Pass[] { return this._passes!; } @@ -39,11 +39,11 @@ export class SubModel { this._subMesh = subMesh; this._inputAssembler!.destroy(); this._inputAssembler!.initialize(subMesh.iaInfo); - if(this._passes![0].batchingScheme === BatchingSchemes.VB_MERGING) this._subMesh.genFlatBuffers(); + if (this._passes![0].batchingScheme === BatchingSchemes.VB_MERGING) { this._subMesh.genFlatBuffers(); } SubModelPool.set(this._handle, SubModelView.SUB_MESH, subMesh.handle); } - get subMesh () { + get subMesh (): RenderingSubMesh { return this._subMesh!; } @@ -52,27 +52,27 @@ export class SubModel { SubModelPool.set(this._handle, SubModelView.PRIORITY, val); } - get priority () { + get priority (): RenderPriority { return this._priority; } - get handle () { + get handle (): SubModelHandle { return this._handle; } - get inputAssembler () { + get inputAssembler (): InputAssembler { return this._inputAssembler!; } - get descriptorSet () { + get descriptorSet (): DescriptorSet { return this._descriptorSet!; } - get patches () { + get patches (): IMacroPatch[] | null { return this._patches; } - public initialize (subMesh: RenderingSubMesh, passes: Pass[], patches: IMacroPatch[] | null = null) { + public initialize (subMesh: RenderingSubMesh, passes: Pass[], patches: IMacroPatch[] | null = null): void { this._device = legacyCC.director.root.device as Device; this._subMesh = subMesh; @@ -81,7 +81,7 @@ export class SubModel { this._handle = SubModelPool.alloc(); this._flushPassInfo(); - if(passes[0].batchingScheme === BatchingSchemes.VB_MERGING) this._subMesh.genFlatBuffers(); + if (passes[0].batchingScheme === BatchingSchemes.VB_MERGING) { this._subMesh.genFlatBuffers(); } _dsInfo.layout = passes[0].localSetLayout; const dsHandle = DSPool.alloc(this._device, _dsInfo); @@ -95,7 +95,7 @@ export class SubModel { this._descriptorSet = DSPool.get(dsHandle); } - public destroy () { + public destroy (): void { DSPool.free(SubModelPool.get(this._handle, SubModelView.DESCRIPTOR_SET)); IAPool.free(SubModelPool.get(this._handle, SubModelView.INPUT_ASSEMBLER)); SubModelPool.free(this._handle); @@ -110,7 +110,7 @@ export class SubModel { this._passes = null; } - public update () { + public update (): void { for (let i = 0; i < this._passes!.length; ++i) { const pass = this._passes![i]; pass.update(); @@ -118,7 +118,7 @@ export class SubModel { this._descriptorSet!.update(); } - public onPipelineStateChanged () { + public onPipelineStateChanged (): void { const passes = this._passes; if (!passes) { return; } @@ -132,7 +132,7 @@ export class SubModel { this._flushPassInfo(); } - public onMacroPatchesStateChanged (patches) { + public onMacroPatchesStateChanged (patches: IMacroPatch[] | null): void { this._patches = patches; const passes = this._passes; @@ -148,7 +148,7 @@ export class SubModel { this._flushPassInfo(); } - protected _flushPassInfo () { + protected _flushPassInfo (): void { const passes = this._passes; if (!passes) { return; } diff --git a/cocos/core/root.ts b/cocos/core/root.ts index e149d0d151..35e34f56a1 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -187,11 +187,11 @@ export class Root { private _modelPools = new Map, Pool>(); private _cameraPool: Pool | null = null; private _lightPools = new Map, Pool>(); - private _fpsTime: number = 0; - private _frameCount: number = 0; - private _fps: number = 0; - private _fixedFPS: number = 0; - private _fixedFPSFrameTime: number = 0; + private _fpsTime = 0; + private _frameCount = 0; + private _fps = 0; + private _fixedFPS = 0; + private _fixedFPSFrameTime = 0; private _poolHandle: RootHandle = NULL_HANDLE; /** @@ -360,7 +360,7 @@ export class Root { const elapsed = this._frameTime * 1000.0; if (this._fixedFPSFrameTime > elapsed) { - // tslint:disable-next-line: only-arrow-functions + setTimeout(function () {}, this._fixedFPSFrameTime - elapsed); } } diff --git a/cocos/core/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts index 151239703d..f898b69461 100644 --- a/cocos/core/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -105,7 +105,7 @@ export function baseNodePolyfill (BaseNode) { * @return {Component} */ BaseNode.prototype._getDependComponent = function (depended) { - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < this._components.length; i++) { const comp = this._components[i]; if (comp !== depended && comp.isValid && !legacyCC.Object._willDestroy(comp)) { @@ -173,7 +173,7 @@ export function baseNodePolyfill (BaseNode) { // promote debug info js.get(BaseNode.prototype, ' INFO ', function () { let path = ''; - // @ts-ignore + // @ts-expect-error let node = this; while (node && !(node instanceof legacyCC.Scene)) { if (path) { @@ -183,7 +183,7 @@ export function baseNodePolyfill (BaseNode) { } node = node._parent; } - // @ts-ignore + // @ts-expect-error return this.name + ', path: ' + path; }); } diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 613fc62697..1f6961312c 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -47,13 +47,10 @@ import { Scene } from './scene'; type Constructor = new (...args: any[]) => T; -// @ts-ignore const Destroying = CCObject.Flags.Destroying; -// @ts-ignore const DontDestroy = CCObject.Flags.DontDestroy; -// @ts-ignore const Deactivating = CCObject.Flags.Deactivating; -// @ts-ignore +// @ts-expect-error const Activating = CCObject.Flags.Activating; const ChangingState = Activating | Deactivating; @@ -337,7 +334,7 @@ export class BaseNode extends CCObject implements ISchedulable { protected _eventProcessor: NodeEventProcessor = new NodeEventProcessor(this); protected _eventMask = 0; - protected _siblingIndex: number = 0; + protected _siblingIndex = 0; protected _registerIfAttached = !EDITOR ? undefined : function (this: BaseNode, register) { if (EditorExtends.Node && EditorExtends.Component) { @@ -374,8 +371,8 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en * Properties configuration function. - * All properties in attrs will be set to the node, - * when the setter of the node is available, + * All properties in attrs will be set to the node, + * when the setter of the node is available, * the property will be set via setter function. * @zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 * @param attrs - Properties to be set to node @@ -403,7 +400,7 @@ export class BaseNode extends CCObject implements ISchedulable { * @en Set parent of the node. * @zh 设置该节点的父节点。 */ - public setParent (value: this | Scene | null, keepWorldTransform: boolean = false) { + public setParent (value: this | Scene | null, keepWorldTransform = false) { if (this._parent === value) { return; } @@ -695,7 +692,7 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en - * Remove itself from its parent node. + * Remove itself from its parent node. * If the node have no parent, then nothing happens. * @zh * 从父节点中删除该节点。 @@ -756,7 +753,7 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en - * Returns the component of supplied type if the node has one attached, null if it doesn't. + * Returns the component of supplied type if the node has one attached, null if it doesn't. * You can also get component in the node by passing in the name of the script. * @zh * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。 @@ -1212,7 +1209,7 @@ export class BaseNode extends CCObject implements ISchedulable { EditorExtends.Component.remove(component._id); } } - // @ts-ignore + // @ts-expect-error else if (component.node !== this) { errorID(3815); } @@ -1225,7 +1222,7 @@ export class BaseNode extends CCObject implements ISchedulable { } } - protected _onSetParent (oldParent: this | null, keepWorldTransform: boolean = false) { + protected _onSetParent (oldParent: this | null, keepWorldTransform = false) { if (this._parent) { if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) { this.walk((node) => { diff --git a/cocos/core/scene-graph/component-scheduler.ts b/cocos/core/scene-graph/component-scheduler.ts index 6e1dc297f4..d28c77b17c 100644 --- a/cocos/core/scene-graph/component-scheduler.ts +++ b/cocos/core/scene-graph/component-scheduler.ts @@ -37,11 +37,8 @@ import { legacyCC } from '../global-exports'; import { error, assert } from '../platform/debug'; const fastRemoveAt = array.fastRemoveAt; -// @ts-ignore const IsStartCalled = CCObject.Flags.IsStartCalled; -// @ts-ignore const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; -// @ts-ignore const IsEditorOnEnableCalled = CCObject.Flags.IsEditorOnEnableCalled; const callerFunctor: any = EDITOR && tryCatchFunctor_EDITOR; @@ -213,7 +210,7 @@ class ReusableInvoker extends LifeCycleInvoker { function enableInEditor (comp) { if (!(comp._objFlags & IsEditorOnEnableCalled)) { legacyCC.engine.emit('component-enabled', comp.uuid); - if(!legacyCC.GAME_VIEW) { + if (!legacyCC.GAME_VIEW) { comp._objFlags |= IsEditorOnEnableCalled; } } @@ -233,8 +230,8 @@ export function createInvokeImplJit (code: string, useDt?, ensureFlag?) { 'var c=a[it.i];' + code + '}'; - let fastPath = useDt ? Function('it', 'dt', body) : Function('it', body); - let singleInvoke = Function('c', 'dt', code); + const fastPath = useDt ? Function('it', 'dt', body) : Function('it', body); + const singleInvoke = Function('c', 'dt', code); return createInvokeImpl(singleInvoke, fastPath, ensureFlag); } export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?) { @@ -245,7 +242,7 @@ export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?) { catch (e) { // slow path legacyCC._throw(e); - var array = iterator.array; + const array = iterator.array; if (ensureFlag) { array[iterator.i]._objFlags |= ensureFlag; } @@ -272,9 +269,9 @@ const invokeStart = SUPPORT_JIT ? createInvokeImplJit('c.start();c._objFlags|=' c._objFlags |= IsStartCalled; }, function (iterator) { - var array = iterator.array; + const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - let comp = array[iterator.i]; + const comp = array[iterator.i]; comp.start(); comp._objFlags |= IsStartCalled; } @@ -288,7 +285,7 @@ const invokeUpdate = SUPPORT_JIT ? createInvokeImplJit('c.update(dt)', true) : c.update(dt); }, function (iterator, dt) { - var array = iterator.array; + const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].update(dt); } @@ -301,7 +298,7 @@ const invokeLateUpdate = SUPPORT_JIT ? createInvokeImplJit('c.lateUpdate(dt)', t c.lateUpdate(dt); }, function (iterator, dt) { - var array = iterator.array; + const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].lateUpdate(dt); } diff --git a/cocos/core/scene-graph/layers.ts b/cocos/core/scene-graph/layers.ts index ffbd79f78b..0820896563 100644 --- a/cocos/core/scene-graph/layers.ts +++ b/cocos/core/scene-graph/layers.ts @@ -33,17 +33,17 @@ import { legacyCC } from '../global-exports'; // built-in layers, users can use 0~19 bits, 20~31 are system preserve bits. const layerList = { - NONE: 0, - IGNORE_RAYCAST : (1 << 20), - GIZMOS : (1 << 21), - EDITOR : (1 << 22), - UI_3D : (1 << 23), - SCENE_GIZMO : (1 << 24), - UI_2D : (1 << 25), + NONE: 0, + IGNORE_RAYCAST: (1 << 20), + GIZMOS: (1 << 21), + EDITOR: (1 << 22), + UI_3D: (1 << 23), + SCENE_GIZMO: (1 << 24), + UI_2D: (1 << 25), - PROFILER : (1 << 28), - DEFAULT : (1 << 30), - ALL : 0xffffffff, + PROFILER: (1 << 28), + DEFAULT: (1 << 30), + ALL: 0xffffffff, }; /** @@ -54,17 +54,17 @@ const layerList = { * Every node can be assigned to multiple layers with different bit masks, you can setup layer with inclusive or exclusive operation. */ export class Layers { - /** * @en All layers in an Enum * @zh 以 Enum 形式存在的所有层列表 */ public static Enum = Enum(layerList); + /** * @en All layers in [[BitMask]] type * @zh 包含所有层的 [[BitMask]] */ - public static BitMask = BitMask(Object.assign({}, layerList)); + public static BitMask = BitMask({ ...layerList }); /** * @en @@ -75,11 +75,11 @@ export class Layers { * @return A filter which can detect all accepted layers */ public static makeMaskInclude (includes: number[]): number { - let mask = 0; - for (const inc of includes) { - mask |= inc; - } - return mask; + let mask = 0; + for (const inc of includes) { + mask |= inc; + } + return mask; } /** @@ -91,7 +91,7 @@ export class Layers { * @return A filter which can detect for excluded layers */ public static makeMaskExclude (excludes: number[]): number { - return ~Layers.makeMaskInclude(excludes); + return ~Layers.makeMaskInclude(excludes); } /** @@ -101,18 +101,18 @@ export class Layers { * @param bitNum Layer's bit position */ public static addLayer (name: string, bitNum: number) { - if ( bitNum === undefined ) { - console.warn('bitNum can\'t be undefined'); - return; - } - if ( bitNum > 19 || bitNum < 0) { - console.warn('maximum layers reached.'); - return; - } - Layers.Enum[name] = 1 << bitNum; - Layers.Enum[bitNum] = name; - Layers.BitMask[name] = 1 << bitNum; - Layers.BitMask[bitNum] = name; + if (bitNum === undefined) { + console.warn('bitNum can\'t be undefined'); + return; + } + if (bitNum > 19 || bitNum < 0) { + console.warn('maximum layers reached.'); + return; + } + Layers.Enum[name] = 1 << bitNum; + Layers.Enum[bitNum] = name; + Layers.BitMask[name] = 1 << bitNum; + Layers.BitMask[bitNum] = name; } /** @@ -121,17 +121,16 @@ export class Layers { * @param bitNum Layer's bit position */ public static deleteLayer (bitNum: number) { - if ( bitNum > 19 || bitNum < 0) { - console.warn('do not change buildin layers.'); - return; - } - delete Layers.Enum[Layers.Enum[bitNum]]; - delete Layers.Enum[bitNum]; - delete Layers.BitMask[Layers.BitMask[bitNum]]; - delete Layers.BitMask[bitNum]; + if (bitNum > 19 || bitNum < 0) { + console.warn('do not change buildin layers.'); + return; + } + delete Layers.Enum[Layers.Enum[bitNum]]; + delete Layers.Enum[bitNum]; + delete Layers.BitMask[Layers.BitMask[bitNum]]; + delete Layers.BitMask[bitNum]; } } - export declare namespace Layers { export type Enum = EnumAlias; export type BitMask = EnumAlias; diff --git a/cocos/core/scene-graph/node-activator.ts b/cocos/core/scene-graph/node-activator.ts index 6c29d11bf8..23cd87b740 100644 --- a/cocos/core/scene-graph/node-activator.ts +++ b/cocos/core/scene-graph/node-activator.ts @@ -38,13 +38,9 @@ import { assert, errorID } from '../platform/debug'; const MAX_POOL_SIZE = 4; -// @ts-ignore const IsPreloadStarted = CCObject.Flags.IsPreloadStarted; -// @ts-ignore const IsOnLoadStarted = CCObject.Flags.IsOnLoadStarted; -// @ts-ignore const IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled; -// @ts-ignore const Deactivating = CCObject.Flags.Deactivating; const callPreloadInTryCatch = EDITOR && tryCatchFunctor_EDITOR('__preload'); @@ -81,9 +77,9 @@ class UnsortedInvoker extends LifeCycleInvoker { const invokePreload = SUPPORT_JIT ? createInvokeImplJit('c.__preload();') : createInvokeImpl( - function (c) { c.__preload(); }, + function (c) { c.__preload(); }, function (iterator) { - var array = iterator.array; + const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { array[iterator.i].__preload(); } @@ -96,9 +92,9 @@ const invokeOnLoad = SUPPORT_JIT ? createInvokeImplJit('c.onLoad();c._objFlags|= c._objFlags |= IsOnLoadCalled; }, function (iterator) { - var array = iterator.array; + const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - let comp = array[iterator.i]; + const comp = array[iterator.i]; comp.onLoad(); comp._objFlags |= IsOnLoadCalled; } @@ -143,7 +139,7 @@ function _componentCorrupted (node, comp, index) { function _onLoadInEditor (comp) { if (comp.onLoad && !legacyCC.GAME_VIEW) { - // @ts-ignore + // @ts-expect-error const focused = Editor.Selection.getLastSelected('node') === comp.node.uuid; if (focused) { if (comp.onFocusInEditor && callOnFocusInTryCatch) { @@ -156,8 +152,8 @@ function _onLoadInEditor (comp) { } } } - if ( !TEST ) { - // @ts-ignore + if (!TEST) { + // @ts-expect-error _Scene.AssetsWatcher.start(comp); } } diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index eac1ab39d5..1edc35815d 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -28,16 +28,22 @@ * @module scene-graph */ -import { ccclass, type, serializable, editable } from 'cc.decorator'; -import { Mat3, Mat4, Quat, Vec3 } from '../math'; +import { + ccclass, editable, serializable, type, +} from 'cc.decorator'; +import { Layers } from './layers'; +import { NodeUIProperties } from './node-ui-properties'; import { SystemEventType } from '../platform/event-manager/event-enum'; import { eventManager } from '../platform/event-manager/event-manager'; -import { BaseNode, TRANSFORM_ON } from './base-node'; -import { Layers } from './layers'; -import { NodeSpace, TransformBit } from './node-enum'; -import { NodeUIProperties } from './node-ui-properties'; import { legacyCC } from '../global-exports'; -import { NodeHandle, NodePool, NodeView, NULL_HANDLE } from '../renderer/core/memory-pools'; +import { BaseNode, TRANSFORM_ON } from './base-node'; +import { + Mat3, Mat4, Quat, Vec3, +} from '../math'; +import { + NULL_HANDLE, NodeHandle, NodePool, NodeView, +} from '../renderer/core/memory-pools'; +import { NodeSpace, TransformBit } from './node-enum'; const v3_a = new Vec3(); const q_a = new Quat(); @@ -47,7 +53,7 @@ const qt_1 = new Quat(); const m3_1 = new Mat3(); const m3_scaling = new Mat3(); const m4_1 = new Mat4(); -const bookOfChange = new Map(); +const bookOfChange = new Map(); /** * @zh @@ -80,48 +86,50 @@ export class Node extends BaseNode { * @zh 节点可能发出的事件类型 */ public static EventType = SystemEventType; + /** * @en Coordinates space * @zh 空间变换操作的坐标系 */ public static NodeSpace = NodeSpace; + /** * @en Bit masks for Node transformation parts * @zh 节点变换更新的具体部分 * @deprecated please use [[Node.TransformBit]] */ public static TransformDirtyBit = TransformBit; + /** * @en Bit masks for Node transformation parts, can be used to determine which part changed in [[SystemEventType.TRANSFORM_CHANGED]] event * @zh 节点变换更新的具体部分,可用于判断 [[SystemEventType.TRANSFORM_CHANGED]] 事件的具体类型 */ public static TransformBit = TransformBit; - /** - * @en Determine whether the given object is a normal Node. Will return false if [[Scene]] given. - * @zh 指定对象是否是普通的节点?如果传入 [[Scene]] 会返回 false。 - */ - public static isNode (obj: object | null): obj is Node { - return obj instanceof Node && (obj.constructor === Node || !(obj instanceof legacyCC.Scene)); - } - // UI 部分的脏数据 public _uiProps = new NodeUIProperties(this); + public _static = false; // world transform, don't access this directly protected _pos = new Vec3(); + protected _rot = new Quat(); + protected _scale = new Vec3(1, 1, 1); + protected _mat = new Mat4(); // local transform @serializable protected _lpos = new Vec3(); + @serializable protected _lrot = new Quat(); + @serializable protected _lscale = new Vec3(1, 1, 1); + @serializable protected _layer = Layers.Enum.DEFAULT; // the layer this node belongs to @@ -130,7 +138,9 @@ export class Node extends BaseNode { protected _euler = new Vec3(); protected _dirtyFlags = TransformBit.NONE; // does the world transform need to update? + protected _eulerDirty = false; + protected _poolHandle: NodeHandle = NULL_HANDLE; constructor (name?: string) { @@ -140,6 +150,14 @@ export class Node extends BaseNode { NodePool.setVec3(this._poolHandle, NodeView.WORLD_SCALE, this._scale); } + /** + * @en Determine whether the given object is a normal Node. Will return false if [[Scene]] given. + * @zh 指定对象是否是普通的节点?如果传入 [[Scene]] 会返回 false。 + */ + public static isNode (obj: unknown): obj is Node { + return obj instanceof Node && (obj.constructor === Node || !(obj instanceof legacyCC.Scene)); + } + public destroy () { if (this._poolHandle) { NodePool.free(this._poolHandle); @@ -148,7 +166,7 @@ export class Node extends BaseNode { return super.destroy(); } - get handle () : NodeHandle { + get handle (): NodeHandle { return this._poolHandle; } @@ -160,6 +178,7 @@ export class Node extends BaseNode { public get position (): Readonly { return this._lpos; } + public set position (val: Readonly) { this.setPosition(val); } @@ -173,6 +192,7 @@ export class Node extends BaseNode { this.updateWorldTransform(); return this._pos; } + public set worldPosition (val: Readonly) { this.setWorldPosition(val); NodePool.setVec3(this._poolHandle, NodeView.WORLD_POSITION, val); @@ -186,6 +206,7 @@ export class Node extends BaseNode { public get rotation (): Readonly { return this._lrot; } + public set rotation (val: Readonly) { this.setRotation(val); } @@ -198,6 +219,7 @@ export class Node extends BaseNode { set eulerAngles (val: Readonly) { this.setRotationFromEuler(val.x, val.y, val.z); } + get eulerAngles () { if (this._eulerDirty) { Quat.toEuler(this._euler, this._lrot); @@ -214,6 +236,7 @@ export class Node extends BaseNode { get angle () { return this._euler.z; } + set angle (val: number) { Vec3.set(this._euler, 0, 0, val); Quat.fromAngleZ(this._lrot, val); @@ -234,6 +257,7 @@ export class Node extends BaseNode { this.updateWorldTransform(); return this._rot; } + public set worldRotation (val: Readonly) { this.setWorldRotation(val); } @@ -246,6 +270,7 @@ export class Node extends BaseNode { public get scale (): Readonly { return this._lscale; } + public set scale (val: Readonly) { this.setScale(val); } @@ -259,6 +284,7 @@ export class Node extends BaseNode { this.updateWorldTransform(); return this._scale; } + public set worldScale (val: Readonly) { this.setWorldScale(val); NodePool.setVec3(this._poolHandle, NodeView.WORLD_SCALE, val); @@ -294,6 +320,7 @@ export class Node extends BaseNode { get forward (): Vec3 { return Vec3.transformQuat(new Vec3(), Vec3.FORWARD, this.worldRotation); } + set forward (dir: Vec3) { const len = dir.length(); Vec3.multiplyScalar(v3_a, dir, -1 / len); @@ -311,6 +338,7 @@ export class Node extends BaseNode { NodePool.set(this._poolHandle, NodeView.LAYER, this._layer); this.emit(SystemEventType.LAYER_CHANGED, this._layer); } + get layer () { return this._layer; } @@ -320,10 +348,11 @@ export class Node extends BaseNode { * @zh 这个节点的空间变换信息在当前帧内是否有变过? */ get hasChangedFlags () { - return bookOfChange.get(this._id) || 0; + return bookOfChange.get(this) || 0; } + set hasChangedFlags (val: number) { - bookOfChange.set(this._id, val); + bookOfChange.set(this, val); NodePool.set(this._poolHandle, NodeView.FLAGS_CHANGED, val); } @@ -337,7 +366,7 @@ export class Node extends BaseNode { * @param value Parent node * @param keepWorldTransform Whether keep node's current world transform unchanged after this operation */ - public setParent (value: this | null, keepWorldTransform: boolean = false) { + public setParent (value: this | null, keepWorldTransform = false) { if (keepWorldTransform) { this.updateWorldTransform(); } super.setParent(value, keepWorldTransform); } @@ -363,7 +392,7 @@ export class Node extends BaseNode { public _onBatchCreated (dontSyncChildPrefab?: boolean) { super._onBatchCreated(); - bookOfChange.set(this._id, TransformBit.TRS); + bookOfChange.set(this, TransformBit.TRS); this._dirtyFlags = TransformBit.TRS; const len = this._children.length; for (let i = 0; i < len; ++i) { @@ -376,7 +405,7 @@ export class Node extends BaseNode { } public _onBeforeSerialize () { - // tslint:disable-next-line: no-unused-expression + // eslint-disable-next-line no-unused-expressions this.eulerAngles; // make sure we save the correct eulerAngles } @@ -481,14 +510,15 @@ export class Node extends BaseNode { * @param dirtyBit The dirty bits to setup to children, can be composed with multiple dirty bits */ public invalidateChildren (dirtyBit: TransformBit) { - if ((this._dirtyFlags & this.hasChangedFlags & dirtyBit) === dirtyBit) { return; } + const hasChanegdFlags = this.hasChangedFlags; + if ((this._dirtyFlags & hasChanegdFlags & dirtyBit) === dirtyBit) { return; } this._dirtyFlags |= dirtyBit; - bookOfChange.set(this._id, this.hasChangedFlags | dirtyBit); - dirtyBit |= TransformBit.POSITION; + bookOfChange.set(this, hasChanegdFlags | dirtyBit); + const newDirtyBit = dirtyBit | TransformBit.POSITION; const len = this._children.length; for (let i = 0; i < len; ++i) { const child = this._children[i]; - if (child.isValid) { child.invalidateChildren(dirtyBit); } + if (child.isValid) { child.invalidateChildren(newDirtyBit); } } } @@ -498,6 +528,8 @@ export class Node extends BaseNode { */ public updateWorldTransform () { if (!this._dirtyFlags) { return; } + // we need to recursively iterate this + // eslint-disable-next-line @typescript-eslint/no-this-alias let cur: this | null = this; let i = 0; while (cur && cur._dirtyFlags) { @@ -580,22 +612,12 @@ export class Node extends BaseNode { * @param y Y axis position * @param z Z axis position */ - public setPosition (x: number, y: number, z: number): void; - - - /** - * @en Set position in local coordinate system - * @zh 设置本地坐标 - * @param x X axis position - * @param y Y axis position - */ - public setPosition (x: number, y: number): void; - + public setPosition (x: number, y: number, z?: number): void; public setPosition (val: Vec3 | number, y?: number, z?: number): void { if (y === undefined && z === undefined) { Vec3.copy(this._lpos, val as Vec3); - } else if( z === undefined) { + } else if (z === undefined) { Vec3.set(this._lpos, val as number, y!, this._lpos.z); } else { Vec3.set(this._lpos, val as number, y!, z); @@ -616,9 +638,8 @@ export class Node extends BaseNode { public getPosition (out?: Vec3): Vec3 { if (out) { return Vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z); - } else { - return Vec3.copy(new Vec3(), this._lpos); } + return Vec3.copy(new Vec3(), this._lpos); } /** @@ -659,8 +680,8 @@ export class Node extends BaseNode { * @param y Y axis rotation * @param z Z axis rotation */ - public setRotationFromEuler (x: number, y: number, z?: number): void { - if(z === undefined) z = this._euler.z; + public setRotationFromEuler (x: number, y: number, zOpt?: number): void { + const z = zOpt === undefined ? this._euler.z : zOpt; Vec3.set(this._euler, x, y, z); Quat.fromEuler(this._lrot, x, y, z); this._eulerDirty = false; @@ -680,9 +701,8 @@ export class Node extends BaseNode { public getRotation (out?: Quat): Quat { if (out) { return Quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w); - } else { - return Quat.copy(new Quat(), this._lrot); } + return Quat.copy(new Quat(), this._lrot); } /** @@ -702,12 +722,12 @@ export class Node extends BaseNode { public setScale (x: number, y: number, z?: number): void; public setScale (val: Vec3 | number, y?: number, z?: number) { - if (y === undefined || z === undefined) { + if (y === undefined && z === undefined) { Vec3.copy(this._lscale, val as Vec3); - } else if( z === undefined) { - Vec3.set(this._lscale, val as number, y, this._lscale.z); + } else if (z === undefined) { + Vec3.set(this._lscale, val as number, y!, this._lscale.z); } else { - Vec3.set(this._lscale, val as number, y, z); + Vec3.set(this._lscale, val as number, y!, z); } this.invalidateChildren(TransformBit.SCALE); @@ -725,9 +745,8 @@ export class Node extends BaseNode { public getScale (out?: Vec3): Vec3 { if (out) { return Vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z); - } else { - return Vec3.copy(new Vec3(), this._lscale); } + return Vec3.copy(new Vec3(), this._lscale); } /** @@ -738,7 +757,10 @@ export class Node extends BaseNode { */ public inverseTransformPoint (out: Vec3, p: Vec3) { Vec3.copy(out, p); - let cur = this; let i = 0; + // we need to recursively iterate this + // eslint-disable-next-line @typescript-eslint/no-this-alias + let cur = this; + let i = 0; while (cur._parent) { array_a[i++] = cur; cur = cur._parent; @@ -803,9 +825,8 @@ export class Node extends BaseNode { this.updateWorldTransform(); if (out) { return Vec3.copy(out, this._pos); - } else { - return Vec3.copy(new Vec3(), this._pos); } + return Vec3.copy(new Vec3(), this._pos); } /** @@ -879,9 +900,8 @@ export class Node extends BaseNode { this.updateWorldTransform(); if (out) { return Quat.copy(out, this._rot); - } else { - return Quat.copy(new Quat(), this._rot); } + return Quat.copy(new Quat(), this._rot); } /** @@ -939,9 +959,8 @@ export class Node extends BaseNode { this.updateWorldTransform(); if (out) { return Vec3.copy(out, this._scale); - } else { - return Vec3.copy(new Vec3(), this._scale); } + return Vec3.copy(new Vec3(), this._scale); } /** @@ -952,8 +971,8 @@ export class Node extends BaseNode { */ public getWorldMatrix (out?: Mat4): Mat4 { this.updateWorldTransform(); - if (!out) { out = new Mat4(); } - return Mat4.copy(out, this._mat); + const target = out || new Mat4(); + return Mat4.copy(target, this._mat); } /** @@ -964,10 +983,10 @@ export class Node extends BaseNode { */ public getWorldRS (out?: Mat4): Mat4 { this.updateWorldTransform(); - if (!out) { out = new Mat4(); } - Mat4.copy(out, this._mat); - out.m12 = 0; out.m13 = 0; out.m14 = 0; - return out; + const target = out || new Mat4(); + Mat4.copy(target, this._mat); + target.m12 = 0; target.m13 = 0; target.m14 = 0; + return target; } /** @@ -978,8 +997,8 @@ export class Node extends BaseNode { */ public getWorldRT (out?: Mat4): Mat4 { this.updateWorldTransform(); - if (!out) { out = new Mat4(); } - return Mat4.fromRT(out, this._rot, this._pos); + const target = out || new Mat4(); + return Mat4.fromRT(target, this._rot, this._pos); } /** @@ -1029,7 +1048,6 @@ export class Node extends BaseNode { * @param recursive Whether pause system events recursively for the child node tree */ public pauseSystemEvents (recursive: boolean): void { - // @ts-ignore eventManager.pauseTarget(this, recursive); } @@ -1045,7 +1063,6 @@ export class Node extends BaseNode { * @param recursive Whether resume system events recursively for the child node tree */ public resumeSystemEvents (recursive: boolean): void { - // @ts-ignore eventManager.resumeTarget(this, recursive); } } diff --git a/cocos/core/scene-graph/private-node.ts b/cocos/core/scene-graph/private-node.ts index 597c6141a1..cc530f1b40 100644 --- a/cocos/core/scene-graph/private-node.ts +++ b/cocos/core/scene-graph/private-node.ts @@ -36,7 +36,6 @@ import { legacyCC } from '../global-exports'; // const LocalDirtyFlag = Node._LocalDirtyFlag; // const POSITION_ON = 1 << 0; -// @ts-ignore const HideInHierarchy = CCObject.Flags.HideInHierarchy; /** @@ -169,8 +168,8 @@ export class PrivateNode extends Node { if (EDITOR) { // check components to avoid missing node reference serialied in previous version PrivateNode.prototype._onBatchCreated = function (dontSyncChildPrefab?: boolean) { - // @ts-ignore - for (let comp of this._components) { + // @ts-expect-error + for (const comp of this._components) { comp.node = this; } diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index ae9170e683..0828c335f7 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -29,12 +29,12 @@ */ import { ccclass, serializable, editable } from 'cc.decorator'; +import { EDITOR, TEST } from 'internal:constants'; import { CCObject } from '../data/object'; import { Mat4, Quat, Vec3 } from '../math'; import { assert, getError } from '../platform/debug'; import { RenderScene } from '../renderer/scene/render-scene'; import { BaseNode } from './base-node'; -import { EDITOR, TEST } from 'internal:constants'; import { legacyCC } from '../global-exports'; import { Component } from '../components/component'; import { SceneGlobals } from './scene-globals'; @@ -78,16 +78,22 @@ export class Scene extends BaseNode { public _globals = new SceneGlobals(); public _renderScene: RenderScene | null = null; + public dependAssets = null; // cache all depend assets for auto release protected _inited: boolean; + protected _prefabSyncedInLiveReload = false; // support Node access parent data from Scene protected _pos = Vec3.ZERO; + protected _rot = Quat.IDENTITY; + protected _scale = Vec3.ONE; + protected _mat = Mat4.IDENTITY; + protected _dirtyFlags = 0; constructor (name: string) { @@ -106,7 +112,7 @@ export class Scene extends BaseNode { public destroy () { const success = CCObject.prototype.destroy.call(this); if (success) { - let children = this._children; + const children = this._children; for (let i = 0; i < children.length; ++i) { children[i].active = false; } @@ -145,70 +151,87 @@ export class Scene extends BaseNode { * Refer to [[Node.getPosition]] */ public getPosition (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } + /** * Refer to [[Node.getRotation]] */ public getRotation (out?: Quat): Quat { return Quat.copy(out || new Quat(), Quat.IDENTITY); } + /** * Refer to [[Node.getScale]] */ public getScale (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ONE); } + /** * Refer to [[Node.getWorldPosition]] */ public getWorldPosition (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } + /** * Refer to [[Node.getWorldRotation]] */ public getWorldRotation (out?: Quat) { return Quat.copy(out || new Quat(), Quat.IDENTITY); } + /** * Refer to [[Node.getWorldScale]] */ public getWorldScale (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ONE); } + /** * Refer to [[Node.getWorldMatrix]] */ public getWorldMatrix (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + /** * Refer to [[Node.getWorldRS]] */ public getWorldRS (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + /** * Refer to [[Node.getWorldRT]] */ public getWorldRT (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + /** * Refer to [[Node.position]] */ public get position (): Readonly { return Vec3.ZERO; } + /** * Refer to [[Node.worldPosition]] */ public get worldPosition (): Readonly { return Vec3.ZERO; } + /** * Refer to [[Node.rotation]] */ public get rotation (): Readonly { return Quat.IDENTITY; } + /** * Refer to [[Node.worldRotation]] */ public get worldRotation (): Readonly { return Quat.IDENTITY; } + /** * Refer to [[Node.scale]] */ public get scale (): Readonly { return Vec3.ONE; } + /** * Refer to [[Node.worldScale]] */ public get worldScale (): Readonly { return Vec3.ONE; } + /** * Refer to [[Node.eulerAngles]] */ public get eulerAngles (): Readonly { return Vec3.ZERO; } + /** * Refer to [[Node.worldMatrix]] */ public get worldMatrix (): Readonly { return Mat4.IDENTITY; } + /** * Refer to [[Node.updateWorldTransform]] */ diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index 1b3625c8e8..a3137984d2 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -56,7 +56,7 @@ export interface ISchedulable { */ class ListEntry { - public static get = (target: ISchedulable, priority: Number, paused: Boolean, markedForDeletion: Boolean) => { + public static get = (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean) => { let result = ListEntry._listEntries.pop(); if (result) { result.target = target; @@ -80,11 +80,11 @@ class ListEntry { private static _listEntries: any = []; public target: ISchedulable; - public priority: Number; - public paused: Boolean; - public markedForDeletion: Boolean; + public priority: number; + public paused: boolean; + public markedForDeletion: boolean; - constructor (target: ISchedulable, priority: Number, paused: Boolean, markedForDeletion: Boolean) { + constructor (target: ISchedulable, priority: number, paused: boolean, markedForDeletion: boolean) { this.target = target; this.priority = priority; this.paused = paused; @@ -152,7 +152,7 @@ class HashUpdateEntry { */ class HashTimerEntry { - public static get = (timers: any, target: ISchedulable, timerIndex: Number, currentTimer: any, currentTimerSalvaged: any, paused: any) => { + public static get = (timers: any, target: ISchedulable, timerIndex: number, currentTimer: any, currentTimerSalvaged: any, paused: any) => { let result = HashTimerEntry._hashTimerEntries.pop(); if (result) { result.timers = timers; @@ -179,12 +179,12 @@ class HashTimerEntry { public timers: any; public target: ISchedulable; - public timerIndex: Number; + public timerIndex: number; public currentTimer: any; public currentTimerSalvaged: any; public paused: any; - constructor (timers: any, target: ISchedulable, timerIndex: Number, currentTimer: any, currentTimerSalvaged: any, paused: any){ + constructor (timers: any, target: ISchedulable, timerIndex: number, currentTimer: any, currentTimerSalvaged: any, paused: any) { this.timers = timers; this.target = target; this.timerIndex = timerIndex; @@ -306,7 +306,7 @@ class CallbackTimer { } } - public getCallback (){ + public getCallback () { return this._callback; } @@ -387,7 +387,7 @@ export class Scheduler extends System { found = true; } if (!found) { - // @ts-ignore + // @ts-expect-error if (target.__instanceId) { warnID(1513); } @@ -458,21 +458,21 @@ export class Scheduler extends System { let len: number; let entry; - for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++){ + for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) { entry = list[i]; if (!entry.paused && !entry.markedForDeletion) { entry.target.update(dt); } } - for ( i = 0, list = this._updates0List, len = list.length; i < len; i++){ + for (i = 0, list = this._updates0List, len = list.length; i < len; i++) { entry = list[i]; if (!entry.paused && !entry.markedForDeletion) { entry.target.update(dt); } } - for ( i = 0, list = this._updatesPosList, len = list.length; i < len; i++){ + for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) { entry = list[i]; if (!entry.paused && !entry.markedForDeletion) { entry.target.update(dt); @@ -482,14 +482,14 @@ export class Scheduler extends System { // Iterate over all the custom selectors let elt; const arr = this._arrayForTimers; - for ( i = 0; i < arr.length; i++){ + for (i = 0; i < arr.length; i++) { elt = arr[i]; this._currentTarget = elt; this._currentTargetSalvaged = false; - if (!elt.paused){ + if (!elt.paused) { // The 'timers' array may change while inside this loop - for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++(elt.timerIndex)){ + for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++(elt.timerIndex)) { elt.currentTimer = elt.timers[elt.timerIndex]; elt.currentTimerSalvaged = false; @@ -507,7 +507,7 @@ export class Scheduler extends System { // delete all updates that are marked for deletion // updates with priority < 0 - for ( i = 0, list = this._updatesNegList; i < list.length; ){ + for (i = 0, list = this._updatesNegList; i < list.length;) { entry = list[i]; if (entry.markedForDeletion) { this._removeUpdateFromHash(entry); @@ -517,7 +517,7 @@ export class Scheduler extends System { } } - for ( i = 0, list = this._updates0List; i < list.length; ){ + for (i = 0, list = this._updates0List; i < list.length;) { entry = list[i]; if (entry.markedForDeletion) { this._removeUpdateFromHash(entry); @@ -527,7 +527,7 @@ export class Scheduler extends System { } } - for ( i = 0, list = this._updatesPosList; i < list.length; ){ + for (i = 0, list = this._updatesPosList; i < list.length;) { entry = list[i]; if (entry.markedForDeletion) { this._removeUpdateFromHash(entry); @@ -572,7 +572,7 @@ export class Scheduler extends System { 'use strict'; if (typeof callback !== 'function') { const tmp = callback; - // @ts-ignore + // @ts-expect-error callback = target; target = tmp; } @@ -586,7 +586,7 @@ export class Scheduler extends System { assertID(target, 1502); - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; @@ -638,26 +638,26 @@ export class Scheduler extends System { * @param priority * @param paused */ - public scheduleUpdate (target: ISchedulable, priority: Number, paused: Boolean) { - let targetId = target.uuid || target.id; + public scheduleUpdate (target: ISchedulable, priority: number, paused: boolean) { + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; } const hashElement = this._hashForUpdates[targetId]; - if (hashElement && hashElement.entry){ + if (hashElement && hashElement.entry) { // check if priority has changed - if (hashElement.entry.priority !== priority){ - if (this._updateHashLocked){ + if (hashElement.entry.priority !== priority) { + if (this._updateHashLocked) { logID(1506); hashElement.entry.markedForDeletion = false; hashElement.entry.paused = paused; return; - }else{ + } else { // will be added again outside if (hashElement). this.unscheduleUpdate(target); } - }else{ + } else { hashElement.entry.markedForDeletion = false; hashElement.entry.paused = paused; return; @@ -699,7 +699,7 @@ export class Scheduler extends System { if (!target || !callback) { return; } - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; @@ -744,7 +744,7 @@ export class Scheduler extends System { if (!target) { return; } - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; @@ -769,10 +769,10 @@ export class Scheduler extends System { */ public unscheduleAllForTarget (target) { // explicit nullptr handling - if (!target){ + if (!target) { return; } - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; @@ -791,9 +791,9 @@ export class Scheduler extends System { } timers.length = 0; - if (this._currentTarget === element){ + if (this._currentTarget === element) { this._currentTargetSalvaged = true; - }else{ + } else { this._removeHashElement(element); } } @@ -810,7 +810,7 @@ export class Scheduler extends System { * 取消所有对象的所有定时器,包括系统定时器。
* 不要调用此函数,除非你确定你在做什么。 */ - public unscheduleAll (){ + public unscheduleAll () { this.unscheduleAllWithMinPriority(legacyCC.Scheduler.PRIORITY_SYSTEM); } @@ -824,12 +824,12 @@ export class Scheduler extends System { * @param minPriority The minimum priority of selector to be unscheduled. Which means, all selectors which * priority is higher than minPriority will be unscheduled. */ - public unscheduleAllWithMinPriority (minPriority: number){ + public unscheduleAllWithMinPriority (minPriority: number) { // Custom Selectors let i; let element; const arr = this._arrayForTimers; - for ( i = arr.length - 1; i >= 0; i--) { + for (i = arr.length - 1; i >= 0; i--) { element = arr[i]; this.unscheduleAllForTarget(element.target); } @@ -837,8 +837,8 @@ export class Scheduler extends System { // Updates selectors let entry; let temp_length = 0; - if (minPriority < 0){ - for ( i = 0; i < this._updatesNegList.length; ) { + if (minPriority < 0) { + for (i = 0; i < this._updatesNegList.length;) { temp_length = this._updatesNegList.length; entry = this._updatesNegList[i]; if (entry && entry.priority >= minPriority) { @@ -850,8 +850,8 @@ export class Scheduler extends System { } } - if (minPriority <= 0 ) { - for ( i = 0; i < this._updates0List.length; ) { + if (minPriority <= 0) { + for (i = 0; i < this._updates0List.length;) { temp_length = this._updates0List.length; entry = this._updates0List[i]; if (entry) { @@ -863,10 +863,10 @@ export class Scheduler extends System { } } - for ( i = 0; i < this._updatesPosList.length; ) { + for (i = 0; i < this._updatesPosList.length;) { temp_length = this._updatesPosList.length; entry = this._updatesPosList[i]; - if ( entry && entry.priority >= minPriority ) { + if (entry && entry.priority >= minPriority) { this.unscheduleUpdate(entry.target); } if (temp_length === this._updatesPosList.length) { @@ -882,12 +882,12 @@ export class Scheduler extends System { * @param target The target of the callback. * @return True if the specified callback is invoked, false if not. */ - public isScheduled (callback, target:ISchedulable){ + public isScheduled (callback, target:ISchedulable) { // key, target // selector, target assertID(callback, 1508); assertID(target, 1509); - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; @@ -899,15 +899,15 @@ export class Scheduler extends System { return false; } - if (element.timers == null){ + if (element.timers == null) { return false; } else { const timers = element.timers; - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < timers.length; ++i) { const timer = timers[i]; - if (callback === timer._callback){ + if (callback === timer._callback) { return true; } } @@ -1002,7 +1002,7 @@ export class Scheduler extends System { if (!targetsToResume) { return; } - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < targetsToResume.length; i++) { this.resumeTarget(targetsToResume[i]); } @@ -1021,7 +1021,7 @@ export class Scheduler extends System { */ public pauseTarget (target:ISchedulable) { assertID(target, 1503); - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; @@ -1054,7 +1054,7 @@ export class Scheduler extends System { */ public resumeTarget (target:ISchedulable) { assertID(target, 1504); - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return; @@ -1081,7 +1081,7 @@ export class Scheduler extends System { */ public isTargetPaused (target:ISchedulable) { assertID(target, 1505); - let targetId = target.uuid || target.id; + const targetId = target.uuid || target.id; if (!targetId) { errorID(1510); return false; @@ -1101,7 +1101,7 @@ export class Scheduler extends System { // -----------------------private method---------------------- private _removeHashElement (element) { - let targetId = element.target.uuid || element.target.id; + const targetId = element.target.uuid || element.target.id; delete this._hashForTimers[targetId]; const arr = this._arrayForTimers; for (let i = 0, l = arr.length; i < l; i++) { @@ -1135,7 +1135,7 @@ export class Scheduler extends System { } private _priorityIn (ppList, listElement, priority) { - for (let i = 0; i < ppList.length; i++){ + for (let i = 0; i < ppList.length; i++) { if (priority < ppList[i].priority) { ppList.splice(i, 0, listElement); return; diff --git a/cocos/core/utils/array.ts b/cocos/core/utils/array.ts index d071129833..058618abcb 100644 --- a/cocos/core/utils/array.ts +++ b/cocos/core/utils/array.ts @@ -179,7 +179,6 @@ export function appendObjectsAt (array: T[], objects: T[], index: number) { * @returns 返回数组是否包含指定的元素。 */ export function contains (array: T[], value: T) { - // eslint-disable-next-line @typescript-eslint/prefer-includes return array.indexOf(value) >= 0; } diff --git a/cocos/core/utils/binary-search.ts b/cocos/core/utils/binary-search.ts index d373cfdfbd..7e66b44415 100644 --- a/cocos/core/utils/binary-search.ts +++ b/cocos/core/utils/binary-search.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ -// tslint:disable + const EPSILON = 1e-6; diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index 0d31bf7f7a..9b74e17cc4 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -29,7 +29,7 @@ * @hidden */ - // tslint:disable + import { getClassName, getset, isEmptyObject } from './js'; import { EDITOR, DEV } from 'internal:constants'; @@ -143,7 +143,7 @@ export function isDomNode (obj) { export function callInNextTick (callback, p1?: any, p2?: any) { if (EDITOR) { if (callback) { - // @ts-ignore + // @ts-expect-error process.nextTick(function () { callback(p1, p2); }); @@ -193,12 +193,12 @@ export function isPlainEmptyObj_DEV (obj) { */ export function clampf (value, min_inclusive, max_inclusive) { if (min_inclusive > max_inclusive) { - var temp = min_inclusive; + const temp = min_inclusive; min_inclusive = max_inclusive; max_inclusive = temp; } return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive; -}; +} /** * @en converts degrees to radians @@ -208,7 +208,7 @@ export function clampf (value, min_inclusive, max_inclusive) { */ export function degreesToRadians (angle) { return angle * macro.RAD; -}; +} /** * @en converts radians to degrees @@ -218,7 +218,7 @@ export function degreesToRadians (angle) { */ export function radiansToDegrees (angle) { return angle * macro.DEG; -}; +} // if (TEST) { // // editor mocks using in unit tests diff --git a/cocos/core/utils/prefab-helper.ts b/cocos/core/utils/prefab-helper.ts index f3708adf03..4220bf7ab7 100644 --- a/cocos/core/utils/prefab-helper.ts +++ b/cocos/core/utils/prefab-helper.ts @@ -89,12 +89,9 @@ export default function syncWithPrefab (node) { // if (!_prefab.asset) { if (EDITOR) { - // @ts-ignore // const NodeUtils = Editor.require('scene://utils/node'); - // // @ts-ignore // const PrefabUtils = Editor.require('scene://utils/prefab'); - // // @ts-ignore // cc.warn(Editor.T('MESSAGE.prefab.missing_prefab', { node: NodeUtils.getNodePath(node) })); // node.name += PrefabUtils.MISSING_PREFAB_SUFFIX; } diff --git a/cocos/core/utils/profiler/profiler.ts b/cocos/core/utils/profiler/profiler.ts index edf87896a7..b7f8bbfcf6 100644 --- a/cocos/core/utils/profiler/profiler.ts +++ b/cocos/core/utils/profiler/profiler.ts @@ -392,9 +392,9 @@ export class Profiler { this.offsetData[2] = this._eachNumWidth; this.offsetData[3] = surfaceTransform; } - - // @ts-ignore + + // @ts-expect-error this.pass._rootBufferDirty = true; } diff --git a/cocos/core/value-types/bitmask.ts b/cocos/core/value-types/bitmask.ts index e3b0aec344..620696f293 100644 --- a/cocos/core/value-types/bitmask.ts +++ b/cocos/core/value-types/bitmask.ts @@ -47,7 +47,7 @@ export function BitMask (obj: T): T { } value(obj, '__bitmask__', null, true); - let lastIndex: number = -1; + let lastIndex = -1; const keys: string[] = Object.keys(obj); for (let i = 0; i < keys.length; i++) { @@ -87,7 +87,7 @@ BitMask.getList = (BitMaskDef) => { } const bitlist: any[] = BitMaskDef.__bitmask__ = []; - // tslint:disable-next-line: forin + for (const name in BitMaskDef) { const v = BitMaskDef[name]; if (Number.isInteger(v)) { diff --git a/cocos/core/value-types/enum.ts b/cocos/core/value-types/enum.ts index 2aace715e9..eaf67124b4 100644 --- a/cocos/core/value-types/enum.ts +++ b/cocos/core/value-types/enum.ts @@ -64,10 +64,10 @@ export function Enum (obj: T): T { * @param obj */ Enum.update = (obj: T): T => { - let lastIndex: number = -1; + let lastIndex = -1; const keys: string[] = Object.keys(obj); - // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < keys.length; i++) { const key = keys[i]; let val = obj[key]; @@ -93,7 +93,7 @@ Enum.update = (obj: T): T => { } } // auto update list if __enums__ is array - if(Array.isArray(obj['__enums__'])) { + if (Array.isArray(obj['__enums__'])) { updateList(obj); } return obj; @@ -125,7 +125,7 @@ Enum.isEnum = (enumType: EnumT) => { return enumType && enumType.hasOwnProperty('__enums__'); }; -function assertIsEnum (enumType: EnumT): asserts enumType is EnumT & EnumExtras { +function assertIsEnum (enumType: EnumT): asserts enumType is EnumT & EnumExtras { assertIsTrue(enumType.hasOwnProperty('__enums__')); } @@ -148,11 +148,11 @@ Enum.getList = (enumType: EnumT): readonly Enum.Enumerator(enumType: EnumT): readonly Enum.Enumerator[] { +function updateList (enumType: EnumT): readonly Enum.Enumerator[] { assertIsEnum(enumType); const enums: any[] = enumType.__enums__ || []; enums.length = 0; - // tslint:disable-next-line: forin + for (const name in enumType) { const v = enumType[name]; if (Number.isInteger(v)) { @@ -162,7 +162,7 @@ function updateList(enumType: EnumT): readonly Enum.Enumerator enums.sort((a, b) => a.value - b.value); enumType.__enums__ = enums; return enums; -}; +} if (DEV) { // check key order in object literal diff --git a/cocos/particle/animator/color-overtime.ts b/cocos/particle/animator/color-overtime.ts index e36e0bc0ba..1553429809 100644 --- a/cocos/particle/animator/color-overtime.ts +++ b/cocos/particle/animator/color-overtime.ts @@ -11,7 +11,7 @@ import GradientRange from './gradient-range'; import { ModuleRandSeed } from '../enum'; import { ParticleModuleBase } from '../particle'; -// tslint:disable: max-line-length + const COLOR_OVERTIME_RAND_OFFSET = ModuleRandSeed.COLOR; diff --git a/cocos/particle/animator/force-overtime.ts b/cocos/particle/animator/force-overtime.ts index dfd53b1a44..69adc7cfed 100644 --- a/cocos/particle/animator/force-overtime.ts +++ b/cocos/particle/animator/force-overtime.ts @@ -12,7 +12,7 @@ import CurveRange from './curve-range'; import { ModuleRandSeed } from '../enum'; import { ParticleModuleBase, PARTICLE_MODULE_NAME} from '../particle'; -// tslint:disable: max-line-length + const FORCE_OVERTIME_RAND_OFFSET = ModuleRandSeed.FORCE; const _temp_v3 = new Vec3(); diff --git a/cocos/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts index c3da3bb353..d764d24b56 100644 --- a/cocos/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -12,7 +12,7 @@ import { EDITOR } from 'internal:constants'; import { Texture2D } from '../../core'; import { PixelFormat, Filter, WrapMode } from '../../core/assets/asset-enum'; -// tslint:disable: max-line-length + const SerializableTable = EDITOR && [ [ '_mode', 'color' ], [ '_mode', 'gradient' ], @@ -174,4 +174,4 @@ export function packGradientRange (samples: number, gr: GradientRange) { texture.uploadData(data); return texture; -} \ No newline at end of file +} diff --git a/cocos/particle/animator/gradient.ts b/cocos/particle/animator/gradient.ts index ac1968a3d5..b1e99d91e9 100644 --- a/cocos/particle/animator/gradient.ts +++ b/cocos/particle/animator/gradient.ts @@ -7,7 +7,7 @@ import { ccclass, serializable, editable } from 'cc.decorator'; import { Color, lerp, repeat } from '../../core/math'; import { Enum } from '../../core/value-types'; -// tslint:disable: max-line-length + const Mode = Enum({ Blend: 0, diff --git a/cocos/particle/animator/limit-velocity-overtime.ts b/cocos/particle/animator/limit-velocity-overtime.ts index 56dbadc20d..faced5d5c2 100644 --- a/cocos/particle/animator/limit-velocity-overtime.ts +++ b/cocos/particle/animator/limit-velocity-overtime.ts @@ -11,7 +11,7 @@ import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle' import CurveRange from './curve-range'; import { calculateTransform } from '../particle-general-function'; -// tslint:disable: max-line-length + const LIMIT_VELOCITY_RAND_OFFSET = ModuleRandSeed.LIMIT; const _temp_v3 = new Vec3(); diff --git a/cocos/particle/animator/optimized-curve.ts b/cocos/particle/animator/optimized-curve.ts index d9852b7bcd..502004321e 100644 --- a/cocos/particle/animator/optimized-curve.ts +++ b/cocos/particle/animator/optimized-curve.ts @@ -7,7 +7,7 @@ import { repeat } from '../../core/math'; import { AnimationCurve, evalOptCurve, OptimizedKey } from '../../core/geometry/curve'; -// tslint:disable: max-line-length + const CURVE_MODE_CONSTANT = 0; const CURVE_MODE_RANDOM_CONSTANT = 1; diff --git a/cocos/particle/animator/rotation-overtime.ts b/cocos/particle/animator/rotation-overtime.ts index b7410ea6b1..bd7c56a4a1 100644 --- a/cocos/particle/animator/rotation-overtime.ts +++ b/cocos/particle/animator/rotation-overtime.ts @@ -10,7 +10,7 @@ import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle' import CurveRange from './curve-range'; import { ModuleRandSeed } from '../enum'; -// tslint:disable: max-line-length + const ROTATION_OVERTIME_RAND_OFFSET = ModuleRandSeed.ROTATION; @ccclass('cc.RotationOvertimeModule') diff --git a/cocos/particle/animator/size-overtime.ts b/cocos/particle/animator/size-overtime.ts index 4a1981774e..b7a068c33a 100644 --- a/cocos/particle/animator/size-overtime.ts +++ b/cocos/particle/animator/size-overtime.ts @@ -10,7 +10,7 @@ import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle' import CurveRange from './curve-range'; import { ModuleRandSeed } from '../enum'; -// tslint:disable: max-line-length + const SIZE_OVERTIME_RAND_OFFSET = ModuleRandSeed.SIZE; @ccclass('cc.SizeOvertimeModule') diff --git a/cocos/particle/animator/texture-animation.ts b/cocos/particle/animator/texture-animation.ts index 91a6257ca4..174285e995 100644 --- a/cocos/particle/animator/texture-animation.ts +++ b/cocos/particle/animator/texture-animation.ts @@ -11,7 +11,7 @@ import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle' import CurveRange from './curve-range'; import { ModuleRandSeed } from '../enum'; -// tslint:disable: max-line-length + const TEXTURE_ANIMATION_RAND_OFFSET = ModuleRandSeed.TEXTURE; /** @@ -214,7 +214,7 @@ export default class TextureAnimationModule extends ParticleModuleBase { @displayOrder(6) @tooltip('从动画贴图中选择特定行以生成动画。\n此选项仅在动画播放方式为 SingleRow 时且禁用 randomRow 时可用') public rowIndex = 0; - + public name = PARTICLE_MODULE_NAME.TEXTURE; public init (p: Particle) { diff --git a/cocos/particle/animator/velocity-overtime.ts b/cocos/particle/animator/velocity-overtime.ts index b4ac67fbc2..b891e65a0f 100644 --- a/cocos/particle/animator/velocity-overtime.ts +++ b/cocos/particle/animator/velocity-overtime.ts @@ -12,7 +12,7 @@ import { calculateTransform } from '../particle-general-function'; import CurveRange from './curve-range'; import { ModuleRandSeed } from '../enum'; -// tslint:disable: max-line-length + const VELOCITY_X_OVERTIME_RAND_OFFSET = ModuleRandSeed.VELOCITY_X; const VELOCITY_Y_OVERTIME_RAND_OFFSET = ModuleRandSeed.VELOCITY_Y; const VELOCITY_Z_OVERTIME_RAND_OFFSET = ModuleRandSeed.VELOCITY_Z; diff --git a/cocos/particle/line.ts b/cocos/particle/line.ts index 4c492d1200..17a9a6b322 100644 --- a/cocos/particle/line.ts +++ b/cocos/particle/line.ts @@ -71,7 +71,7 @@ export class Line extends Component { define[CC_USE_WORLD_SPACE] = this.worldSpace; this._materialInstance.recompileShaders(define); if (this._model) { - this._model.setSubModelMaterial(0, this._materialInstance!); + this._model.setSubModelMaterial(0, this._materialInstance); } } } @@ -190,7 +190,7 @@ export class Line extends Component { public onLoad () { const model = this._model = legacyCC.director.root.createModel(LineModel); model.node = model.transform = this.node; - if (this._material == null) { + if (this._material === null) { this._material = new Material(); this._material.copy(builtinResMgr.get('default-trail-material')); define[CC_USE_WORLD_SPACE] = this.worldSpace; @@ -207,8 +207,8 @@ export class Line extends Component { if (!this._model) { return; } - this.attachToScene(); - this.texture = this.texture; + this._attachToScene(); + this.texture = this._texture; this.tile = this._tile; this.offset = this._offset; this._model.addLineVertexData(this._positions, this._width, this._color); @@ -216,20 +216,20 @@ export class Line extends Component { public onDisable () { if (this._model) { - this.detachFromScene(); + this._detachFromScene(); } } - private attachToScene () { + protected _attachToScene () { if (this._model && this.node && this.node.scene) { if (this._model.scene) { - this.detachFromScene(); + this._detachFromScene(); } this._getRenderScene().addModel(this._model); } } - private detachFromScene () { + protected _detachFromScene () { if (this._model && this._model.scene) { this._model.scene.removeModel(this._model); } diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index ddd478fb30..41b2941dea 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -5,7 +5,7 @@ * @module particle */ -// tslint:disable: max-line-length + import { RenderableComponent } from '../core/3d/framework/renderable-component'; import { Material } from '../core/assets/material'; @@ -55,9 +55,9 @@ export class ParticleSystem extends RenderableComponent { public set capacity (val) { this._capacity = Math.floor(val); - // @ts-ignore + // @ts-expect-error if (this.processor && this.processor._model) { - // @ts-ignore + // @ts-expect-error this.processor._model.setCapacity(this._capacity); } } @@ -289,12 +289,12 @@ export class ParticleSystem extends RenderableComponent { @visible(false) get sharedMaterials () { // if we don't create an array copy, the editor will modify the original array directly. - // @ts-ignore + // @ts-expect-error return superMaterials.get.call(this); } set sharedMaterials (val) { - // @ts-ignore + // @ts-expect-error superMaterials.set.call(this, val); } @@ -311,7 +311,7 @@ export class ParticleSystem extends RenderableComponent { if (EDITOR) { if (!this._colorOverLifetimeModule) { this._colorOverLifetimeModule = new ColorOverLifetimeModule(); - this._colorOverLifetimeModule.bindTarget(this.processor!); + this._colorOverLifetimeModule.bindTarget(this.processor); } } return this._colorOverLifetimeModule; @@ -359,7 +359,7 @@ export class ParticleSystem extends RenderableComponent { if (EDITOR) { if (!this._sizeOvertimeModule) { this._sizeOvertimeModule = new SizeOvertimeModule(); - this._sizeOvertimeModule.bindTarget(this.processor!); + this._sizeOvertimeModule.bindTarget(this.processor); } } return this._sizeOvertimeModule; @@ -383,7 +383,7 @@ export class ParticleSystem extends RenderableComponent { if (EDITOR) { if (!this._velocityOvertimeModule) { this._velocityOvertimeModule = new VelocityOvertimeModule(); - this._velocityOvertimeModule.bindTarget(this.processor!); + this._velocityOvertimeModule.bindTarget(this.processor); } } return this._velocityOvertimeModule; @@ -407,7 +407,7 @@ export class ParticleSystem extends RenderableComponent { if (EDITOR) { if (!this._forceOvertimeModule) { this._forceOvertimeModule = new ForceOvertimeModule(); - this._forceOvertimeModule.bindTarget(this.processor!); + this._forceOvertimeModule.bindTarget(this.processor); } } return this._forceOvertimeModule; @@ -432,7 +432,7 @@ export class ParticleSystem extends RenderableComponent { if (EDITOR) { if (!this._limitVelocityOvertimeModule) { this._limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); - this._limitVelocityOvertimeModule.bindTarget(this.processor!); + this._limitVelocityOvertimeModule.bindTarget(this.processor); } } return this._limitVelocityOvertimeModule; @@ -456,7 +456,7 @@ export class ParticleSystem extends RenderableComponent { if (EDITOR) { if (!this._rotationOvertimeModule) { this._rotationOvertimeModule = new RotationOvertimeModule(); - this._rotationOvertimeModule.bindTarget(this.processor!); + this._rotationOvertimeModule.bindTarget(this.processor); } } return this._rotationOvertimeModule; @@ -480,7 +480,7 @@ export class ParticleSystem extends RenderableComponent { if (EDITOR) { if (!this._textureAnimationModule) { this._textureAnimationModule = new TextureAnimationModule(); - this._textureAnimationModule.bindTarget(this.processor!); + this._textureAnimationModule.bindTarget(this.processor); } } return this._textureAnimationModule; @@ -527,7 +527,7 @@ export class ParticleSystem extends RenderableComponent { @serializable @displayOrder(27) @tooltip('是否剔除非 enable 的模块数据') - public enableCulling: boolean = false; + public enableCulling = false; /** * @ignore @@ -597,11 +597,11 @@ export class ParticleSystem extends RenderableComponent { } public _onMaterialModified (index: number, material: Material) { - this.processor!.onMaterialModified(index, material); + this.processor.onMaterialModified(index, material); } public _onRebuildPSO (index: number, material: Material) { - this.processor!.onRebuildPSO(index, material); + this.processor.onRebuildPSO(index, material); } public _collectModels (): scene.Model[] { @@ -614,27 +614,27 @@ export class ParticleSystem extends RenderableComponent { } protected _attachToScene () { - this.processor!.attachToScene(); + this.processor.attachToScene(); if (this._trailModule && this._trailModule.enable) { this._trailModule._attachToScene(); } } protected _detachFromScene () { - this.processor!.detachFromScene(); + this.processor.detachFromScene(); if (this._trailModule && this._trailModule.enable) { this._trailModule._detachFromScene(); } } public bindModule () { - if (this._colorOverLifetimeModule) this._colorOverLifetimeModule.bindTarget(this.processor!); - if (this._sizeOvertimeModule) this._sizeOvertimeModule.bindTarget(this.processor!); - if (this._rotationOvertimeModule) this._rotationOvertimeModule.bindTarget(this.processor!); - if (this._forceOvertimeModule) this._forceOvertimeModule.bindTarget(this.processor!); - if (this._limitVelocityOvertimeModule) this._limitVelocityOvertimeModule.bindTarget(this.processor!); - if (this._velocityOvertimeModule) this._velocityOvertimeModule.bindTarget(this.processor!); - if (this._textureAnimationModule) this._textureAnimationModule.bindTarget(this.processor!); + if (this._colorOverLifetimeModule) this._colorOverLifetimeModule.bindTarget(this.processor); + if (this._sizeOvertimeModule) this._sizeOvertimeModule.bindTarget(this.processor); + if (this._rotationOvertimeModule) this._rotationOvertimeModule.bindTarget(this.processor); + if (this._forceOvertimeModule) this._forceOvertimeModule.bindTarget(this.processor); + if (this._limitVelocityOvertimeModule) this._limitVelocityOvertimeModule.bindTarget(this.processor); + if (this._velocityOvertimeModule) this._velocityOvertimeModule.bindTarget(this.processor); + if (this._textureAnimationModule) this._textureAnimationModule.bindTarget(this.processor); } // TODO: Fast forward current particle system by simulating particles over given period of time, then pause it. @@ -706,7 +706,7 @@ export class ParticleSystem extends RenderableComponent { */ public clear () { if (this.enabledInHierarchy) { - this.processor!.clear(); + this.processor.clear(); if (this._trailModule) this._trailModule.clear(); } } @@ -715,7 +715,7 @@ export class ParticleSystem extends RenderableComponent { * @zh 获取当前粒子数量 */ public getParticleCount () { - return this.processor!.getParticleCount(); + return this.processor.getParticleCount(); } /** @@ -731,7 +731,7 @@ export class ParticleSystem extends RenderableComponent { protected onDestroy () { // this._system.remove(this); - this.processor!.onDestroy(); + this.processor.onDestroy(); if (this._trailModule) this._trailModule.destroy(); } @@ -739,11 +739,11 @@ export class ParticleSystem extends RenderableComponent { if (this.playOnAwake) { this.play(); } - this.processor!.onEnable(); + this.processor.onEnable(); if (this._trailModule) this._trailModule.onEnable(); } protected onDisable () { - this.processor!.onDisable(); + this.processor.onDisable(); if (this._trailModule) this._trailModule.onDisable(); } protected update (dt: number) { @@ -755,12 +755,12 @@ export class ParticleSystem extends RenderableComponent { this._emit(scaledDeltaTime); // simulation, update particles. - if (this.processor!.updateParticles(scaledDeltaTime) === 0 && !this._isEmitting) { + if (this.processor.updateParticles(scaledDeltaTime) === 0 && !this._isEmitting) { this.stop(); } // update render data - this.processor!.updateRenderData(); + this.processor.updateRenderData(); // update trail if (this._trailModule && this._trailModule.enable) { @@ -770,9 +770,9 @@ export class ParticleSystem extends RenderableComponent { } protected _onVisibilityChange (val) { - // @ts-ignore + // @ts-expect-error if (this.processor._model) { - // @ts-ignore + // @ts-expect-error this.processor._model.visFlags = val; } } @@ -786,7 +786,7 @@ export class ParticleSystem extends RenderableComponent { } for (let i = 0; i < count; ++i) { - const particle = this.processor!.getFreeParticle(); + const particle = this.processor.getFreeParticle(); if (particle === null) { return; } @@ -841,7 +841,7 @@ export class ParticleSystem extends RenderableComponent { particle.randomSeed = randomRangeInt(0, 233280); - this.processor!.setNewParticle(particle); + this.processor.setNewParticle(particle); } // end of particles forLoop. } @@ -855,7 +855,7 @@ export class ParticleSystem extends RenderableComponent { for (let i = 0; i < cnt; ++i) { this._time += dt; this._emit(dt); - this.processor!.updateParticles(dt); + this.processor.updateParticles(dt); } } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index d6801520e0..ffcb6c3eef 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -19,7 +19,7 @@ import { Space, TextureMode, TrailMode } from '../enum'; import { Particle } from '../particle'; import { legacyCC } from '../../core/global-exports'; -// tslint:disable: max-line-length + const PRE_TRIANGLE_INDEX = 1; const NEXT_TRIANGLE_INDEX = 1 << 2; const DIRECTION_THRESHOLD = Math.cos(toRadian(100)); @@ -32,8 +32,8 @@ const _temp_vec3_1 = new Vec3(); const _temp_color = new Color(); const barycentric = [1, 0, 0, 0, 1, 0, 0, 0, 1]; // -// tslint:disable-next-line: prefer-const -let _bcIdx = 0; + +const _bcIdx = 0; interface ITrailElement { position: Vec3; @@ -281,12 +281,12 @@ export default class TrailModule { @serializable private _particleSystem: any = null; - private _minSquaredDistance: number = 0; + private _minSquaredDistance = 0; private _vertSize: number; - private _trailNum: number = 0; - private _trailLifetime: number = 0; - private vbOffset: number = 0; - private ibOffset: number = 0; + private _trailNum = 0; + private _trailLifetime = 0; + private vbOffset = 0; + private ibOffset = 0; private _trailSegments: Pool | null = null; private _particleTrail: Map; private _trailModel: scene.Model | null = null; @@ -297,7 +297,7 @@ export default class TrailModule { private _vbF32: Float32Array | null = null; private _vbUint32: Uint32Array | null = null; private _iBuffer: Uint16Array | null = null; - private _needTransform: boolean = false; + private _needTransform = false; private _material: Material | null = null; constructor () { @@ -546,8 +546,8 @@ export default class TrailModule { const subModels = this._trailModel && this._trailModel.subModels; if (subModels && subModels.length > 0) { const subModel = subModels[0]; - subModel.inputAssembler!.vertexBuffers[0].update(this._vbF32!); - subModel.inputAssembler!.indexBuffer!.update(this._iBuffer!); + subModel.inputAssembler.vertexBuffers[0].update(this._vbF32!); + subModel.inputAssembler.indexBuffer!.update(this._iBuffer!); this._iaInfo.drawInfos[0].firstIndex = 0; this._iaInfo.drawInfos[0].indexCount = count; this._iaInfoBuffer!.update(this._iaInfo); @@ -594,7 +594,7 @@ export default class TrailModule { this._iaInfo.drawInfos[0].indexCount = this._trailNum * 6; this._iaInfoBuffer.update(this._iaInfo); - this._subMeshData = new RenderingSubMesh([vertexBuffer], this._vertAttrs!, PrimitiveMode.TRIANGLE_LIST, indexBuffer, this._iaInfoBuffer); + this._subMeshData = new RenderingSubMesh([vertexBuffer], this._vertAttrs, PrimitiveMode.TRIANGLE_LIST, indexBuffer, this._iaInfoBuffer); const trailModel = this._trailModel; if (trailModel) { diff --git a/cocos/physics/cocos/builtin-shared-body.ts b/cocos/physics/cocos/builtin-shared-body.ts index b26587e67a..0a718ac686 100644 --- a/cocos/physics/cocos/builtin-shared-body.ts +++ b/cocos/physics/cocos/builtin-shared-body.ts @@ -11,7 +11,7 @@ import { BuiltinShape } from './shapes/builtin-shape'; import { Node } from '../../core'; import { BuiltinRigidBody } from './builtin-rigid-body'; import { PhysicsSystem } from '../framework'; -// tslint:disable: prefer-for-of + const m4_0 = new Mat4(); const v3_0 = new Vec3(); @@ -78,10 +78,10 @@ export class BuiltinSharedBody extends BuiltinObject { } /** id generator */ - private static idCounter: number = 0; + private static idCounter = 0; private readonly _id: number; - private index: number = -1; - private ref: number = 0; + private index = -1; + private ref = 0; readonly node: Node; readonly world: BuiltInWorld; diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index 89a620f867..48e14bfe1c 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -42,7 +42,7 @@ export class TerrainInfo { */ @serializable @editable - public tileSize: number = 1; + public tileSize = 1; /** * @en block count @@ -58,7 +58,7 @@ export class TerrainInfo { */ @serializable @editable - public weightMapSize: number = 128; + public weightMapSize = 128; /** * @en light map size @@ -66,7 +66,7 @@ export class TerrainInfo { */ @serializable @editable - public lightMapSize: number = 128; + public lightMapSize = 128; /** * @en terrain size @@ -125,7 +125,7 @@ export class TerrainLayer { */ @serializable @editable - public tileSize: number = 1; + public tileSize = 1; } /** @@ -138,7 +138,7 @@ class TerrainRenderable extends RenderableComponent { public _brushMaterial: Material | null = null; public _currentMaterial: Material | null = null; - public _currentMaterialLayers: number = 0; + public _currentMaterialLayers = 0; public destroy () { // this._invalidMaterial(); @@ -243,16 +243,16 @@ export class TerrainBlockLightmapInfo { public texture: Texture2D|null = null; @serializable @editable - public UOff: number = 0; + public UOff = 0; @serializable @editable - public VOff: number = 0; + public VOff = 0; @serializable @editable - public UScale: number = 0; + public UScale = 0; @serializable @editable - public VScale: number = 0; + public VScale = 0; } /** @@ -277,16 +277,14 @@ export class TerrainBlock { this._lightmapInfo = t._getLightmapInfo(i, j); this._node = new PrivateNode(''); - // @ts-ignore this._node.setParent(this._terrain.node); - // @ts-ignore this._node._objFlags |= legacyCC.Object.Flags.DontSave; - this._renderable = this._node.addComponent(TerrainRenderable) as TerrainRenderable; + this._renderable = this._node.addComponent(TerrainRenderable) ; } public build () { - const gfxDevice = director.root!.device as Device; + const gfxDevice = director.root!.device ; // vertex buffer const vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY); @@ -697,12 +695,12 @@ export class Terrain extends Component { @type(CCBoolean) @serializable @disallowAnimation - protected _receiveShadow: boolean = false; + protected _receiveShadow = false; - protected _tileSize: number = 1; + protected _tileSize = 1; protected _blockCount: number[] = [1, 1]; - protected _weightMapSize: number = 128; - protected _lightMapSize: number = 128; + protected _weightMapSize = 128; + protected _lightMapSize = 128; protected _heights: Uint16Array = new Uint16Array(); protected _weights: Uint8Array = new Uint8Array(); protected _normals: number[] = []; @@ -1429,7 +1427,7 @@ export class Terrain extends Component { * @param step ray step * @param worldSpace is world space */ - public rayCheck (start: Vec3, dir: Vec3, step: number, worldSpace: boolean = true) { + public rayCheck (start: Vec3, dir: Vec3, step: number, worldSpace = true) { const MAX_COUNT = 2000; const trace = start; @@ -1558,7 +1556,7 @@ export class Terrain extends Component { } } - private _buildImp (restore: boolean = false) { + private _buildImp (restore = false) { if (this.valid) { return true; } @@ -1775,7 +1773,7 @@ export class Terrain extends Component { for (let v = 0; v < info.weightMapSize; ++v) { for (let u = 0; u < info.weightMapSize; ++u) { - // tslint:disable-next-line: no-shadowed-variable + let w: Vec4; if (info.weightMapSize === oldWeightMapSize) { w = getOldWeight(u + uOff, v + vOff, this._weights); diff --git a/cocos/tiledmap/tiled-map.ts b/cocos/tiledmap/tiled-map.ts index f17c3c6485..7814fc235c 100644 --- a/cocos/tiledmap/tiled-map.ts +++ b/cocos/tiledmap/tiled-map.ts @@ -79,7 +79,7 @@ export class TiledMap extends Component { _mapSize: Size = new Size(0, 0); _tileSize: Size = new Size(0, 0); - _preloaded: boolean = false; + _preloaded = false; _mapOrientation = Orientation.ORTHO; @@ -125,7 +125,7 @@ export class TiledMap extends Component { * 是否开启瓦片地图的自动裁减功能。瓦片地图如果设置了 skew, rotation 或者采用了摄像机的话,需要手动关闭,否则渲染会出错。 */ @serializable - protected _enableCulling: boolean = true; + protected _enableCulling = true; get enableCulling () { return this._enableCulling; } @@ -138,7 +138,7 @@ export class TiledMap extends Component { } @serializable - protected cleanupImageCache: boolean = true; + protected cleanupImageCache = true; /** @@ -369,7 +369,7 @@ export class TiledMap extends Component { } } - const mapInfo = new TMXMapInfo(file.tmxXmlStr!, tsxContentMap, spfTexturesMap, spfTextureSizeMap, imageLayerTextures); + const mapInfo = new TMXMapInfo(file.tmxXmlStr, tsxContentMap, spfTexturesMap, spfTextureSizeMap, imageLayerTextures); const tilesets = mapInfo.getTilesets(); if (!tilesets || tilesets.length === 0) { logID(7241); @@ -418,7 +418,7 @@ export class TiledMap extends Component { const layerNode = layerInfo.node; // Tiled layer sync anchor to map because it's old behavior, // do not change the behavior avoid influence user's existed logic. - layerNode!._uiProps!.uiTransformComp!.setAnchorPoint(anchor); + layerNode._uiProps.uiTransformComp!.setAnchorPoint(anchor); } for (i = 0, l = this._groups.length; i < l; i++) { @@ -428,8 +428,8 @@ export class TiledMap extends Component { // do not change the behavior avoid influence user's existing logic. groupNode.anchorX = 0.5; groupNode.anchorY = 0.5; - const x = groupInfo.offset!.x - leftTopX + groupNode.width * groupNode.anchorX; - const y = groupInfo.offset!.y + leftTopY - groupNode.height * groupNode.anchorY; + const x = groupInfo.offset.x - leftTopX + groupNode.width * groupNode.anchorX; + const y = groupInfo.offset.y + leftTopY - groupNode.height * groupNode.anchorY; groupInfo.node.setPosition(x, y); } @@ -457,7 +457,7 @@ export class TiledMap extends Component { _buildLayerAndGroup () { const tilesets = this._tilesets; - const texGrids = this._texGrids!; + const texGrids = this._texGrids; const animations = this._animations; texGrids.clear(); @@ -515,9 +515,9 @@ export class TiledMap extends Component { child.active = layerInfo.visible; if (layerInfo instanceof TMXLayerInfo) { - let layer = child!.getComponent(TiledLayer); + let layer = child.getComponent(TiledLayer); if (!layer) { - layer = child!.addComponent(TiledLayer); + layer = child.addComponent(TiledLayer); } layer.init(layerInfo, mapInfo, tilesets, textures, texGrids); @@ -577,7 +577,7 @@ export class TiledMap extends Component { this._mapSize = mapInfo.getMapSize(); this._tileSize = mapInfo.getTileSize(); this._mapOrientation = mapInfo.orientation!; - this._properties = mapInfo.properties!; + this._properties = mapInfo.properties; this._tileProperties = mapInfo.getTileProperties(); this._imageLayers = mapInfo.getImageLayers(); this._animations = mapInfo.getTileAnimations(); @@ -591,7 +591,7 @@ export class TiledMap extends Component { const tilesetInfo = tilesets[i]; if (!tilesetInfo || !tilesetInfo.sourceImage) continue; this._textures[i] = tilesetInfo.sourceImage; - totalTextures.push(tilesetInfo.sourceImage!); + totalTextures.push(tilesetInfo.sourceImage); } for (let i = 0; i < this._imageLayers.length; i++) { @@ -617,7 +617,7 @@ export class TiledMap extends Component { texture._image.src = ''; } else if (sys.capabilities.imageBitmap && texture._image instanceof ImageBitmap) { - // tslint:disable-next-line: no-unused-expression + texture._image.close && texture._image.close(); } texture._image = null; @@ -625,7 +625,7 @@ export class TiledMap extends Component { update (dt: number) { const animations = this._animations; - const texGrids = this._texGrids!; + const texGrids = this._texGrids; for (const aniGID of animations.keys()) { const animation = animations.get(aniGID)!; const frames = animation.frames; diff --git a/cocos/ui/assembler/label/ttf.ts b/cocos/ui/assembler/label/ttf.ts index f42f126659..918fcc42fe 100644 --- a/cocos/ui/assembler/label/ttf.ts +++ b/cocos/ui/assembler/label/ttf.ts @@ -86,7 +86,7 @@ export const ttf: IAssembler = { const data3 = dataList[3]; /* */ node.updateWorldTransform(); - // @ts-ignore + // @ts-expect-error const pos = node._pos as Vec3; const rot = node._rot; const scale = node._scale; const ax = data0.x * scale.x; const bx = data3.x * scale.x; const ay = data0.y * scale.y; const by = data3.y * scale.y; diff --git a/cocos/ui/components/mask.ts b/cocos/ui/components/mask.ts index 01a63ddd95..2212d67028 100644 --- a/cocos/ui/components/mask.ts +++ b/cocos/ui/components/mask.ts @@ -268,7 +268,7 @@ export class Mask extends UIRenderable { } this._alphaThreshold = value; - if(this.type === MaskType.IMAGE_STENCIL) { + if (this.type === MaskType.IMAGE_STENCIL) { this._graphics?.getMaterialInstance(0)?.setProperty('alphaThreshold', this._alphaThreshold); } } @@ -397,7 +397,7 @@ export class Mask extends UIRenderable { } if (this._clearStencilMtl) { - this._clearStencilMtl!.destroy(); + this._clearStencilMtl.destroy(); } this._removeGraphics(); @@ -450,7 +450,7 @@ export class Mask extends UIRenderable { return; } - render.commitComp(this, null, this._postAssembler!); + render.commitComp(this, null, this._postAssembler); } protected _nodeStateChange (type: TransformBit) { @@ -539,13 +539,13 @@ export class Mask extends UIRenderable { if (!this._clearModel) { const mtl = builtinResMgr.get('builtin-clear-stencil'); this._clearStencilMtl = new MaterialInstance({ - parent: mtl!, + parent: mtl, owner: this, subModelIdx: 0, }); this._clearModel = director.root!.createModel(scene.Model); - // @ts-ignore + // @ts-expect-error this._clearModel.name = 'clear-model'; this._clearModel.node = this._clearModel.transform = this.node; let renderMesh: RenderingSubMesh; @@ -611,7 +611,7 @@ export class Mask extends UIRenderable { } } - protected _useRenderData (){ + protected _useRenderData () { if (this._type === MaskType.IMAGE_STENCIL && !this._renderData) { if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); @@ -621,19 +621,19 @@ export class Mask extends UIRenderable { } protected _attachClearModel () { - if (this._clearModel){ + if (this._clearModel) { const renderScene = director.root!.ui.renderScene; renderScene.addModel(this._clearModel); } } - protected _detachClearModel (){ + protected _detachClearModel () { if (this._clearModel) { const renderScene = director.root!.ui.renderScene; - renderScene.removeModel(this._clearModel!); + renderScene.removeModel(this._clearModel); } } } -// tslint:disable-next-line + legacyCC.Mask = Mask; diff --git a/cocos/ui/components/page-view.ts b/cocos/ui/components/page-view.ts index f5729e8802..de68752869 100644 --- a/cocos/ui/components/page-view.ts +++ b/cocos/ui/components/page-view.ts @@ -106,7 +106,6 @@ enum EventType { @help('i18n:cc.PageView') @executionOrder(110) @menu('UI/PageView') -// @ts-ignore export class PageView extends ScrollView { /** * @en @@ -117,11 +116,11 @@ export class PageView extends ScrollView { */ @type(SizeMode) @tooltip('页面视图中每个页面大小类型') - get sizeMode() { + get sizeMode () { return this._sizeMode; } - set sizeMode(value) { + set sizeMode (value) { if (this._sizeMode === value) { return; } @@ -139,11 +138,11 @@ export class PageView extends ScrollView { */ @type(Direction) @tooltip('页面视图滚动类型') - get direction() { + get direction () { return this._direction; } - set direction(value) { + set direction (value) { if (this._direction === value) { return; } @@ -163,11 +162,11 @@ export class PageView extends ScrollView { @slide @range([0, 1, 0.01]) @tooltip('滚动临界值,默认单位百分比,当拖拽超出该数值时,松开会自动滚动下一页,小于时则还原') - get scrollThreshold() { + get scrollThreshold () { return this._scrollThreshold; } - set scrollThreshold(value) { + set scrollThreshold (value) { if (this._scrollThreshold === value) { return; } @@ -206,11 +205,11 @@ export class PageView extends ScrollView { */ @type(PageViewIndicator) @tooltip('页面视图指示器组件') - get indicator() { + get indicator () { return this._indicator; } - set indicator(value) { + set indicator (value) { if (this._indicator === value) { return; } @@ -221,7 +220,7 @@ export class PageView extends ScrollView { } } - get curPageIdx() { + get curPageIdx () { return this._curPageIdx; } @@ -324,7 +323,7 @@ export class PageView extends ScrollView { protected _touchBeganPosition = new Vec3(); protected _touchEndPosition = new Vec3(); - public onEnable() { + public onEnable () { super.onEnable(); this.node.on(SystemEventType.SIZE_CHANGED, this._updateAllPagesSize, this); if (!EDITOR || legacyCC.GAME_VIEW) { @@ -332,7 +331,7 @@ export class PageView extends ScrollView { } } - public onDisable() { + public onDisable () { super.onDisable(); this.node.off(SystemEventType.SIZE_CHANGED, this._updateAllPagesSize, this); if (!EDITOR || legacyCC.GAME_VIEW) { @@ -340,7 +339,7 @@ export class PageView extends ScrollView { } } - public onLoad() { + public onLoad () { this._initPages(); if (this.indicator) { this.indicator.setPageView(this); @@ -356,7 +355,7 @@ export class PageView extends ScrollView { * * @returns 当前页面索引。 */ - public getCurrentPageIndex() { + public getCurrentPageIndex () { return this._curPageIdx; } @@ -368,7 +367,7 @@ export class PageView extends ScrollView { * 设置当前页面索引。 * @param index 索引。 */ - public setCurrentPageIndex(index: number) { + public setCurrentPageIndex (index: number) { this.scrollToPage(index, 1); } @@ -381,7 +380,7 @@ export class PageView extends ScrollView { * * @returns 输=视图所有页面。 */ - public getPages() { + public getPages () { return this._pages; } @@ -394,7 +393,7 @@ export class PageView extends ScrollView { * * @param page 新视图。 */ - public addPage(page: Node) { + public addPage (page: Node) { if (!page || this._pages.indexOf(page) !== -1 || !this.content) { return; } @@ -417,7 +416,7 @@ export class PageView extends ScrollView { * @param page 新视图。 * @param index 指定位置。 */ - public insertPage(page: Node, index: number) { + public insertPage (page: Node, index: number) { if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) { return; } @@ -445,7 +444,7 @@ export class PageView extends ScrollView { * * @param page 指定页面。 */ - public removePage(page: Node) { + public removePage (page: Node) { if (!page || !this.content) { return; } const index = this._pages.indexOf(page); if (index === -1) { @@ -464,7 +463,7 @@ export class PageView extends ScrollView { * * @param index 页面下标。 */ - public removePageAtIndex(index: number) { + public removePageAtIndex (index: number) { const pageList = this._pages; if (index < 0 || index >= pageList.length) { return; } const page = pageList[index]; @@ -481,7 +480,7 @@ export class PageView extends ScrollView { * @zh * 移除所有页面。 */ - public removeAllPages() { + public removeAllPages () { if (!this.content) { return; } const locPages = this._pages; for (let i = 0, len = locPages.length; i < len; i++) { @@ -501,7 +500,7 @@ export class PageView extends ScrollView { * @param idx index of page. * @param timeInSecond scrolling time. */ - public scrollToPage(idx: number, timeInSecond = 0.3) { + public scrollToPage (idx: number, timeInSecond = 0.3) { if (idx < 0 || idx >= this._pages.length) { return; } @@ -514,12 +513,12 @@ export class PageView extends ScrollView { } // override the method of ScrollView - public getScrollEndedEventTiming() { + public getScrollEndedEventTiming () { return this.pageTurningEventTiming; } // 刷新页面视图 - protected _updatePageView() { + protected _updatePageView () { // 当页面数组变化时修改 content 大小 if (!this.content) { return; @@ -555,8 +554,8 @@ export class PageView extends ScrollView { } // 刷新所有页面的大小 - protected _updateAllPagesSize() { - let viewTrans = this.view; + protected _updateAllPagesSize () { + const viewTrans = this.view; if (!this.content || !viewTrans) { return; } @@ -571,7 +570,7 @@ export class PageView extends ScrollView { } } - protected _handleReleaseLogic() { + protected _handleReleaseLogic () { this._autoScrollToPage(); if (this._scrolling) { this._scrolling = false; @@ -581,36 +580,36 @@ export class PageView extends ScrollView { } } - protected _onTouchBegan(event: EventTouch, captureListeners: any) { + protected _onTouchBegan (event: EventTouch, captureListeners: any) { event.touch!.getUILocation(_temp_vec2); Vec3.set(this._touchBeganPosition, _temp_vec2.x, _temp_vec2.y, 0); super._onTouchBegan(event, captureListeners); } - protected _onTouchMoved(event: EventTouch, captureListeners: any) { + protected _onTouchMoved (event: EventTouch, captureListeners: any) { super._onTouchMoved(event, captureListeners); } - protected _onTouchEnded(event: EventTouch, captureListeners: any) { + protected _onTouchEnded (event: EventTouch, captureListeners: any) { event.touch!.getUILocation(_temp_vec2); Vec3.set(this._touchEndPosition, _temp_vec2.x, _temp_vec2.y, 0); super._onTouchEnded(event, captureListeners); } - protected _onTouchCancelled(event: EventTouch, captureListeners: any) { + protected _onTouchCancelled (event: EventTouch, captureListeners: any) { event.touch!.getUILocation(_temp_vec2); Vec3.set(this._touchEndPosition, _temp_vec2.x, _temp_vec2.y, 0); super._onTouchCancelled(event, captureListeners); } - protected _onMouseWheel() { } + protected _onMouseWheel () { } - protected _syncScrollDirection() { + protected _syncScrollDirection () { this.horizontal = this.direction === Direction.Horizontal; this.vertical = this.direction === Direction.Vertical; } - protected _syncSizeMode() { + protected _syncSizeMode () { const viewTrans = this.view; if (!this.content || !viewTrans) { return; } const layout = this.content.getComponent(Layout); @@ -632,7 +631,7 @@ export class PageView extends ScrollView { } // 初始化页面 - protected _initPages() { + protected _initPages () { if (!this.content) { return; } this._initContentPos = this.content.position; const children = this.content.children; @@ -646,7 +645,7 @@ export class PageView extends ScrollView { this._updatePageView(); } - protected _dispatchPageTurningEvent() { + protected _dispatchPageTurningEvent () { if (this._lastPageIdx === this._curPageIdx) { return; } this._lastPageIdx = this._curPageIdx; ComponentEventHandler.emitEvents(this.pageEvents, this, EventType.PAGE_TURNING); @@ -654,7 +653,7 @@ export class PageView extends ScrollView { } // 快速滑动 - protected _isQuicklyScrollable(touchMoveVelocity: Vec3) { + protected _isQuicklyScrollable (touchMoveVelocity: Vec3) { if (this.direction === Direction.Horizontal) { if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) { return true; @@ -669,7 +668,7 @@ export class PageView extends ScrollView { } // 通过 idx 获取偏移值数值 - protected _moveOffsetValue(idx: number) { + protected _moveOffsetValue (idx: number) { const offset = new Vec3(); if (this._sizeMode === SizeMode.Free) { if (this.direction === Direction.Horizontal) { @@ -693,7 +692,7 @@ export class PageView extends ScrollView { return offset; } - protected _getDragDirection(moveOffset: Vec3) { + protected _getDragDirection (moveOffset: Vec3) { if (this._direction === Direction.Horizontal) { if (moveOffset.x === 0) { return 0; @@ -712,7 +711,7 @@ export class PageView extends ScrollView { } // 是否超过自动滚动临界值 - protected _isScrollable(offset: Vec3, index: number, nextIndex: number) { + protected _isScrollable (offset: Vec3, index: number, nextIndex: number) { if (this._sizeMode === SizeMode.Free) { let curPageCenter = 0; let nextPageCenter = 0; @@ -741,7 +740,7 @@ export class PageView extends ScrollView { } } - protected _autoScrollToPage() { + protected _autoScrollToPage () { const bounceBackStarted = this._startBounceBackIfNeeded(); if (bounceBackStarted) { let bounceBackAmount = this._getHowMuchOutOfBoundary(); diff --git a/cocos/ui/components/rich-text.ts b/cocos/ui/components/rich-text.ts index 2223814c58..b560ba86e6 100644 --- a/cocos/ui/components/rich-text.ts +++ b/cocos/ui/components/rich-text.ts @@ -63,7 +63,7 @@ const pool = new Pool((labelSeg: ILabelSegment) => { return false; } else { - let outline = labelSeg.node.getComponent(LabelOutline); + const outline = labelSeg.node.getComponent(LabelOutline); if (outline) { outline.width = 0; } @@ -71,7 +71,7 @@ const pool = new Pool((labelSeg: ILabelSegment) => { return true; }, 20); -// @ts-ignore +// @ts-expect-error pool.get = function (str: string, richtext: RichText) { let labelSeg = this._get(); if (!labelSeg) { @@ -102,7 +102,7 @@ pool.get = function (str: string, richtext: RichText) { // label._forceUseCanvas = true; labelNode.setPosition(0, 0, 0); - let trans = labelNode._uiProps.uiTransformComp!; + const trans = labelNode._uiProps.uiTransformComp!; trans.setAnchorPoint(0.5, 0.5); const labelObj: ILabelSegment = { @@ -413,11 +413,11 @@ export class RichText extends UIComponent { @serializable protected _maxWidth = 0; @serializable - protected _fontFamily: string = 'Arial'; + protected _fontFamily = 'Arial'; @serializable protected _font: TTFFont | null = null; @serializable - protected _isSystemFontUsed: boolean = true; + protected _isSystemFontUsed = true; @serializable protected _userDefinedFont: TTFFont | null = null; @serializable @@ -508,8 +508,8 @@ export class RichText extends UIComponent { } protected _createFontLabel (str: string): ILabelSegment { - // @ts-ignore - return pool.get(str, this); + // @ts-expect-error + return pool.get(str, this)!; } protected _onTTFLoaded () { @@ -519,11 +519,10 @@ export class RichText extends UIComponent { this._updateRichText(); } else { - const self = this; assetManager.postLoadNative(this._font, (err) => { - if (!self.isValid) { return; } - self._layoutDirty = true; - self._updateRichText(); + if (!this.isValid) { return; } + this._layoutDirty = true; + this._updateRichText(); }); } } @@ -534,19 +533,18 @@ export class RichText extends UIComponent { } protected _measureText (styleIndex: number, string?: string) { - const self = this; const func = (s: string) => { let label: ILabelSegment; - if (self._labelSegmentsCache.length === 0) { - label = self._createFontLabel(s); - self._labelSegmentsCache.push(label); + if (this._labelSegmentsCache.length === 0) { + label = this._createFontLabel(s); + this._labelSegmentsCache.push(label); } else { - label = self._labelSegmentsCache[0]; + label = this._labelSegmentsCache[0]; label.node.getComponent(Label)!.string = s; } label.styleIndex = styleIndex; - self._applyTextAttribute(label); + this._applyTextAttribute(label); const labelSize = label.node._uiProps.uiTransformComp!.contentSize; return labelSize.width; }; @@ -561,13 +559,12 @@ export class RichText extends UIComponent { protected _onTouchEnded (event: EventTouch) { const components = this.node.getComponents(Component); - const self = this; for (const seg of this._labelSegments) { const clickHandler = seg.clickHandler; const clickParam = seg.clickParam; if (clickHandler && this._containsTouchLocation(seg, event.touch!.getUILocation())) { components.forEach((component) => { - const func = component[clickHandler] as Function; + const func = component[clickHandler]; if (component.enabledInHierarchy && func) { func.call(component, event, clickParam); } @@ -588,7 +585,7 @@ export class RichText extends UIComponent { } protected _resetState () { - const children = this.node.children as Mutable; + const children = this.node.children ; for (let i = children.length - 1; i >= 0; i--) { const child = children[i]; @@ -650,7 +647,6 @@ export class RichText extends UIComponent { labelSegment.lineCount = this._lineCount; labelSegment.node._uiProps.uiTransformComp!.setAnchorPoint(0, 0); this._applyTextAttribute(labelSegment); - // @ts-ignore this.node.addChild(labelSegment.node); this._labelSegments.push(labelSegment); @@ -729,7 +725,7 @@ export class RichText extends UIComponent { if (oldItem.text !== newItem.text) { return true; } else { - let oldStyle = oldItem.style, newStyle = newItem.style; + const oldStyle = oldItem.style, newStyle = newItem.style; if (oldStyle) { if (newStyle) { if (!!newStyle.outline !== !!oldStyle.outline) { @@ -793,7 +789,6 @@ export class RichText extends UIComponent { // Why need to set spriteFrame before can add child ?? sprite.spriteFrame = spriteFrame; - // @ts-ignore this.node.addChild(spriteNode); const obj: ILabelSegment = { node: spriteNode, @@ -845,7 +840,7 @@ export class RichText extends UIComponent { obj.clickHandler = ''; obj.clickParam = ''; - let event = style.event; + const event = style.event; if (event) { obj.clickHandler = event['click']; obj.clickParam = event['param']; @@ -999,12 +994,12 @@ export class RichText extends UIComponent { nextTokenX += segment.node._uiProps.uiTransformComp!.width; } - let sprite = segment.node.getComponent(Sprite); + const sprite = segment.node.getComponent(Sprite); if (sprite) { - let position = segment.node.position.clone(); + const position = segment.node.position.clone(); // adjust img align (from ) - let lineHeightSet = this._lineHeight; - let lineHeightReal = this._lineHeight * (1 + BASELINE_RATIO); //single line node height + const lineHeightSet = this._lineHeight; + const lineHeightReal = this._lineHeight * (1 + BASELINE_RATIO); //single line node height switch (segment.node._uiProps.uiTransformComp!.anchorY) { case 1: position.y += (lineHeightSet + ((lineHeightReal - lineHeightSet) / 2)); @@ -1018,14 +1013,14 @@ export class RichText extends UIComponent { } // adjust img offset (from ) if (segment.imageOffset) { - let offsets = segment.imageOffset.split(','); + const offsets = segment.imageOffset.split(','); if (offsets.length === 1 && offsets[0]) { - let offsetY = parseFloat(offsets[0]); + const offsetY = parseFloat(offsets[0]); if (Number.isInteger(offsetY)) position.y += offsetY; } else if (offsets.length === 2) { - let offsetX = parseFloat(offsets[0]); - let offsetY = parseFloat(offsets[1]); + const offsetX = parseFloat(offsets[0]); + const offsetY = parseFloat(offsets[1]); if (Number.isInteger(offsetX)) position.x += offsetX; if (Number.isInteger(offsetY)) position.y += offsetY; } @@ -1034,9 +1029,9 @@ export class RichText extends UIComponent { } //adjust y for label with outline - let outline = segment.node.getComponent(LabelOutline); + const outline = segment.node.getComponent(LabelOutline); if (outline) { - let position = segment.node.position.clone(); + const position = segment.node.position.clone(); position.y = position.y - outline.width; segment.node.position = position; } @@ -1091,7 +1086,7 @@ export class RichText extends UIComponent { labelSeg.clickHandler = ''; labelSeg.clickParam = ''; - let event = textStyle.event; + const event = textStyle.event; if (event) { labelSeg.clickHandler = event['click'] || ''; labelSeg.clickParam = event['param'] || ''; @@ -1103,7 +1098,7 @@ export class RichText extends UIComponent { label.cacheMode = this._cacheMode; - let isAsset = this._font instanceof Font; + const isAsset = this._font instanceof Font; if (isAsset && !this._isSystemFontUsed) { label.font = this._font; } else { diff --git a/cocos/ui/components/safe-area.ts b/cocos/ui/components/safe-area.ts index fc6f395c61..3e5c0aaed8 100644 --- a/cocos/ui/components/safe-area.ts +++ b/cocos/ui/components/safe-area.ts @@ -34,8 +34,6 @@ import { UITransform } from '../../core/components/ui-base'; import { view } from '../../core/platform'; import { Widget } from './widget'; import { legacyCC } from "../../core/global-exports"; - -// @ts-ignore import { EDITOR } from 'internal:constants'; /** @@ -62,7 +60,6 @@ import { EDITOR } from 'internal:constants'; @executeInEditMode @menu('UI/SafeArea') @requireComponent(Widget) -// @ts-ignore export class SafeArea extends Component { public onEnable () { @@ -70,7 +67,7 @@ export class SafeArea extends Component { view.on('canvas-resize', this.updateArea, this); } - public onDisable() { + public onDisable () { view.off('canvas-resize', this.updateArea, this); } @@ -84,13 +81,13 @@ export class SafeArea extends Component { */ public updateArea () { // TODO Remove Widget dependencies in the future - let widget = this.node.getComponent(Widget); - let uiTransComp = this.node.getComponent(UITransform); + const widget = this.node.getComponent(Widget); + const uiTransComp = this.node.getComponent(UITransform); if (!widget || !uiTransComp) { return; } - let { winSize, sys } = legacyCC; + const { winSize, sys } = legacyCC; if (EDITOR) { widget.top = widget.bottom = widget.left = widget.right = 0; @@ -99,12 +96,12 @@ export class SafeArea extends Component { } // IMPORTANT: need to update alignment to get the latest position widget.updateAlignment(); - let lastPos = this.node.position; - let lastAnchorPoint = uiTransComp.anchorPoint; + const lastPos = this.node.position; + const lastAnchorPoint = uiTransComp.anchorPoint; // widget.isAlignTop = widget.isAlignBottom = widget.isAlignLeft = widget.isAlignRight = true; - let screenWidth = winSize.width, screenHeight = winSize.height; - let safeArea = sys.getSafeAreaRect(); + const screenWidth = winSize.width, screenHeight = winSize.height; + const safeArea = sys.getSafeAreaRect(); console.log(safeArea); @@ -114,9 +111,9 @@ export class SafeArea extends Component { widget.right = screenWidth - safeArea.x - safeArea.width; widget.updateAlignment(); // set anchor, keep the original position unchanged - let curPos = this.node.position; - let anchorX = lastAnchorPoint.x - (curPos.x - lastPos.x) / uiTransComp.width; - let anchorY = lastAnchorPoint.y - (curPos.y - lastPos.y) / uiTransComp.height; + const curPos = this.node.position; + const anchorX = lastAnchorPoint.x - (curPos.x - lastPos.x) / uiTransComp.width; + const anchorY = lastAnchorPoint.y - (curPos.y - lastPos.y) / uiTransComp.height; uiTransComp.setAnchorPoint(anchorX, anchorY); // IMPORTANT: restore to lastPos even if widget is not ALWAYS widget.enabled = true; diff --git a/cocos/ui/components/sprite.ts b/cocos/ui/components/sprite.ts index 6436368e70..b55bb7fcf9 100644 --- a/cocos/ui/components/sprite.ts +++ b/cocos/ui/components/sprite.ts @@ -227,7 +227,6 @@ export class Sprite extends UIRenderable { this.markForUpdateRenderData(false); this._applySpriteFrame(lastSprite); if (EDITOR) { - // @ts-ignore this.node.emit(EventType.SPRITE_FRAME_CHANGED, this); } } @@ -439,7 +438,7 @@ export class Sprite extends UIRenderable { return this._sizeMode; } set sizeMode (value) { - if (this._sizeMode === value){ + if (this._sizeMode === value) { return; } @@ -487,7 +486,7 @@ export class Sprite extends UIRenderable { this.node.on(SystemEventType.SIZE_CHANGED, this._resized, this); } - if(this._spriteFrame){ + if (this._spriteFrame) { this._spriteFrame.on('load', this._markForUpdateUvDirty, this); this._markForUpdateUvDirty(); } @@ -588,7 +587,7 @@ export class Sprite extends UIRenderable { // return false; // } // return true; - if (!super._canRender()){ + if (!super._canRender()) { return false; } @@ -734,11 +733,11 @@ export class Sprite extends UIRenderable { // } if (this._renderData) { - if(oldFrame){ + if (oldFrame) { oldFrame.off('load', this._markForUpdateUvDirty); } - if(spriteFrame){ + if (spriteFrame) { spriteFrame.on('load', this._markForUpdateUvDirty, this); } @@ -746,11 +745,11 @@ export class Sprite extends UIRenderable { if (oldFrame && spriteFrame) { this._renderData.uvDirty = oldFrame.uvHash !== spriteFrame.uvHash; } else { - this._renderData!.uvDirty = true; + this._renderData.uvDirty = true; } } - this._renderDataFlag = this._renderData!.uvDirty + this._renderDataFlag = this._renderData.uvDirty } if (spriteFrame) { diff --git a/cocos/ui/components/ui-mesh-renderer.ts b/cocos/ui/components/ui-mesh-renderer.ts index 8230402031..cb0b61adb5 100644 --- a/cocos/ui/components/ui-mesh-renderer.ts +++ b/cocos/ui/components/ui-mesh-renderer.ts @@ -134,7 +134,7 @@ export class UIMeshRenderer extends UIComponent { const passNum = passes.length; for (let j = 0; j < passNum; j++) { const pass = passes[j]; - // @ts-ignore + // @ts-expect-error pass._priority = RenderPriority.MAX - 11; if (!pass.blendState.targets[0].blend) { material.overridePipelineStates({ blendState: { targets: [ { blend: true } ] } }, j); diff --git a/cocos/ui/components/widget-manager.ts b/cocos/ui/components/widget-manager.ts index 56ea57c60a..d7d4b96fb0 100644 --- a/cocos/ui/components/widget-manager.ts +++ b/cocos/ui/components/widget-manager.ts @@ -66,7 +66,6 @@ function align (node: Node, widget: Widget) { const useGlobal = target instanceof Scene || !target.getComponent(UITransform); const targetAnchor = useGlobal ? _defaultAnchor : target.getComponent(UITransform)!.anchorPoint; - // @ts-ignore const isRoot = !EDITOR && useGlobal; node.getPosition(_tempPos); const uiTrans = node._uiProps.uiTransformComp!; @@ -201,12 +200,10 @@ function align (node: Node, widget: Widget) { function visitNode (node: any) { const widget = node.getComponent(Widget); if (widget) { - // @ts-ignore if (DEV) { widget._validateTargetInDEV(); } align(node, widget); - // @ts-ignore if ((!EDITOR || widgetManager.animationState!.animatedSinceLastFrame) && widget.alignMode === AlignMode.ONCE) { widget.enabled = false; } else { @@ -355,7 +352,7 @@ export const widgetManager = legacyCC._widgetManager = { if (EDITOR) { View.instance.on('design-resolution-changed', this.onResized, this); } else { - let thisOnResized = this.onResized.bind(this); + const thisOnResized = this.onResized.bind(this); View.instance.on('canvas-resize', thisOnResized); window.addEventListener('orientationchange', thisOnResized); } @@ -407,7 +404,7 @@ export const widgetManager = legacyCC._widgetManager = { const parentTrans = widgetParent._uiProps && widgetParent._uiProps.uiTransformComp; const parentAP = parentTrans ? parentTrans.anchorPoint : _defaultAnchor; const trans = widgetNode._uiProps.uiTransformComp!; - const matchSize = getReadonlyNodeSize(widgetParent!); + const matchSize = getReadonlyNodeSize(widgetParent); const myAP = trans.anchorPoint; const pos = widgetNode.getPosition(); const alignFlags = AlignFlags; @@ -419,7 +416,7 @@ export const widgetManager = legacyCC._widgetManager = { let l = -parentAP.x * matchSize.width; l += zero.x; l *= one.x; - temp = pos.x - myAP.x * trans.width! * widgetNodeScale.x - l; + temp = pos.x - myAP.x * trans.width * widgetNodeScale.x - l; if (!widget.isAbsoluteLeft) { temp /= matchSize.width; } @@ -431,7 +428,7 @@ export const widgetManager = legacyCC._widgetManager = { if (e & alignFlags.RIGHT) { let r = (1 - parentAP.x) * matchSize.width; r += zero.x; - temp = (r *= one.x) - (pos.x + (1 - myAP.x) * trans.width! * widgetNodeScale.x); + temp = (r *= one.x) - (pos.x + (1 - myAP.x) * trans.width * widgetNodeScale.x); if (!widget.isAbsoluteRight) { temp /= matchSize.width; } @@ -443,7 +440,7 @@ export const widgetManager = legacyCC._widgetManager = { if (e & alignFlags.TOP) { let t = (1 - parentAP.y) * matchSize.height; t += zero.y; - temp = (t *= one.y) - (pos.y + (1 - myAP.y) * trans.height! * widgetNodeScale.y); + temp = (t *= one.y) - (pos.y + (1 - myAP.y) * trans.height * widgetNodeScale.y); if (!widget.isAbsoluteTop) { temp /= matchSize.height; } @@ -456,7 +453,7 @@ export const widgetManager = legacyCC._widgetManager = { let b = -parentAP.y * matchSize.height; b += zero.y; b *= one.y; - temp = pos.y - myAP.y * trans.height! * widgetNodeScale.y - b; + temp = pos.y - myAP.y * trans.height * widgetNodeScale.y - b; if (!widget.isAbsoluteBottom) { temp /= matchSize.height; } diff --git a/cocos/ui/components/widget.ts b/cocos/ui/components/widget.ts index 21e96a5792..487a9aeb55 100644 --- a/cocos/ui/components/widget.ts +++ b/cocos/ui/components/widget.ts @@ -49,7 +49,6 @@ const _zeroVec3 = new Vec3(); // returns a readonly size of the node export function getReadonlyNodeSize (parent: Node | Scene) { if (parent instanceof Scene) { - // @ts-ignore if (EDITOR) { // const canvasComp = parent.getComponentInChildren(Canvas); if (!View.instance) { @@ -773,7 +772,7 @@ export class Widget extends Component { * ``` */ public updateAlignment () { - legacyCC._widgetManager.updateAlignment(this.node as Node); + legacyCC._widgetManager.updateAlignment(this.node); } public _validateTargetInDEV () { @@ -823,18 +822,17 @@ export class Widget extends Component { return; } - const self = this; - const newPos = self.node.getPosition(); + const newPos = this.node.getPosition(); const oldPos = this._lastPos; const delta = new Vec3(newPos); delta.subtract(oldPos); - let target = self.node.parent; + let target = this.node.parent; const inverseScale = new Vec3(1, 1, 1); - if (self.target) { - target = self.target; - computeInverseTransForTarget(self.node, target, new Vec3(), inverseScale); + if (this.target) { + target = this.target; + computeInverseTransForTarget(this.node, target, new Vec3(), inverseScale); } if (!target) { return; @@ -846,23 +844,23 @@ export class Widget extends Component { Vec3.set(deltaInPercent, delta.x / targetSize.width, delta.y / targetSize.height, deltaInPercent.z); } - if (self.isAlignTop) { - self._top -= (self._isAbsTop ? delta.y : deltaInPercent.y) * inverseScale.y; + if (this.isAlignTop) { + this._top -= (this._isAbsTop ? delta.y : deltaInPercent.y) * inverseScale.y; } - if (self.isAlignBottom) { - self._bottom += (self._isAbsBottom ? delta.y : deltaInPercent.y) * inverseScale.y; + if (this.isAlignBottom) { + this._bottom += (this._isAbsBottom ? delta.y : deltaInPercent.y) * inverseScale.y; } - if (self.isAlignLeft) { - self._left += (self._isAbsLeft ? delta.x : deltaInPercent.x) * inverseScale.x; + if (this.isAlignLeft) { + this._left += (this._isAbsLeft ? delta.x : deltaInPercent.x) * inverseScale.x; } - if (self.isAlignRight) { - self._right -= (self._isAbsRight ? delta.x : deltaInPercent.x) * inverseScale.x; + if (this.isAlignRight) { + this._right -= (this._isAbsRight ? delta.x : deltaInPercent.x) * inverseScale.x; } - if (self.isAlignHorizontalCenter) { - self._horizontalCenter += (self._isAbsHorizontalCenter ? delta.x : deltaInPercent.x) * inverseScale.x; + if (this.isAlignHorizontalCenter) { + this._horizontalCenter += (this._isAbsHorizontalCenter ? delta.x : deltaInPercent.x) * inverseScale.x; } - if (self.isAlignVerticalCenter) { - self._verticalCenter += (self._isAbsVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; + if (this.isAlignVerticalCenter) { + this._verticalCenter += (this._isAbsVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; } this._recursiveDirty(); } @@ -878,17 +876,16 @@ export class Widget extends Component { this.setDirty(); - const self = this; - const trans = self.node._uiProps.uiTransformComp!; + const trans = this.node._uiProps.uiTransformComp!; const newSize = trans.contentSize; const oldSize = this._lastSize; const delta = new Vec3(newSize.width - oldSize.width, newSize.height - oldSize.height, 0); - let target = self.node.parent; + let target = this.node.parent; const inverseScale = new Vec3(1, 1, 1); - if (self.target) { - target = self.target; - computeInverseTransForTarget(self.node, target, new Vec3(), inverseScale); + if (this.target) { + target = this.target; + computeInverseTransForTarget(this.node, target, new Vec3(), inverseScale); } if (!target) { return; @@ -902,17 +899,17 @@ export class Widget extends Component { const anchor = trans.anchorPoint; - if (self.isAlignTop) { - self._top -= (self._isAbsTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; + if (this.isAlignTop) { + this._top -= (this._isAbsTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; } - if (self.isAlignBottom) { - self._bottom -= (self._isAbsBottom ? delta.y : deltaInPercent.y) * anchor.y * inverseScale.y; + if (this.isAlignBottom) { + this._bottom -= (this._isAbsBottom ? delta.y : deltaInPercent.y) * anchor.y * inverseScale.y; } - if (self.isAlignLeft) { - self._left -= (self._isAbsLeft ? delta.x : deltaInPercent.x) * anchor.x * inverseScale.x; + if (this.isAlignLeft) { + this._left -= (this._isAbsLeft ? delta.x : deltaInPercent.x) * anchor.x * inverseScale.x; } - if (self.isAlignRight) { - self._right -= (self._isAbsRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; + if (this.isAlignRight) { + this._right -= (this._isAbsRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; } this._recursiveDirty(); } @@ -1019,7 +1016,7 @@ export class Widget extends Component { this.isAlignHorizontalCenter = false; if (this.isStretchWidth) { // become stretch - this._originalWidth = trans.width!; + this._originalWidth = trans.width; // test check conflict if (EDITOR /*&& !cc.engine.isPlaying*/) { // TODO: @@ -1030,7 +1027,7 @@ export class Widget extends Component { this.isAlignVerticalCenter = false; if (this.isStretchHeight) { // become stretch - this._originalHeight = trans.height!; + this._originalHeight = trans.height; // test check conflict if (EDITOR /*&& !cc.engine.isPlaying*/) { // TODO: diff --git a/editor/exports/offline-mappings.ts b/editor/exports/offline-mappings.ts index 533587bd49..194f23f44d 100644 --- a/editor/exports/offline-mappings.ts +++ b/editor/exports/offline-mappings.ts @@ -274,7 +274,7 @@ const effectStructure = { }; export { - murmurhash2_32_gc, + murmurhash2_32_gc as murmurhash2_32_gc, SamplerInfoIndex, genSamplerHash, effectStructure, diff --git a/package-lock.json b/package-lock.json index 1167232f27..cd4abb5a6f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1252,7 +1252,7 @@ }, "@babel/preset-env": { "version": "7.8.7", - "resolved": "https://registry.npm.taobao.org/@babel/preset-env/download/@babel/preset-env-7.8.7.tgz?cache=0&sync_timestamp=1593522855920&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40babel%2Fpreset-env%2Fdownload%2F%40babel%2Fpreset-env-7.8.7.tgz", + "resolved": "https://registry.npm.taobao.org/@babel/preset-env/download/@babel/preset-env-7.8.7.tgz", "integrity": "sha1-H8fYnH910tcMK2do3mwuBJs8uds=", "dev": true, "requires": { @@ -1677,7 +1677,7 @@ }, "source-map": { "version": "0.6.1", - "resolved": "https://registry.npm.taobao.org/source-map/download/source-map-0.6.1.tgz?cache=0&sync_timestamp=1571657176668&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsource-map%2Fdownload%2Fsource-map-0.6.1.tgz", + "resolved": "https://registry.npm.taobao.org/source-map/download/source-map-0.6.1.tgz", "integrity": "sha1-dHIq8y6WFOnCh6jQu95IteLxomM=", "dev": true }, @@ -1702,7 +1702,7 @@ "dependencies": { "fs-extra": { "version": "8.1.0", - "resolved": "https://registry.npm.taobao.org/fs-extra/download/fs-extra-8.1.0.tgz?cache=0&sync_timestamp=1591229972229&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Ffs-extra%2Fdownload%2Ffs-extra-8.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/fs-extra/download/fs-extra-8.1.0.tgz", "integrity": "sha1-SdQ8RaiM2Wd2aMt74bRu/bjS4cA=", "dev": true, "requires": { @@ -1715,7 +1715,7 @@ }, "typescript": { "version": "3.7.5", - "resolved": "https://registry.npm.taobao.org/typescript/download/typescript-3.7.5.tgz?cache=0&sync_timestamp=1594620477415&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Ftypescript%2Fdownload%2Ftypescript-3.7.5.tgz", + "resolved": "https://registry.npm.taobao.org/typescript/download/typescript-3.7.5.tgz?cache=0&sync_timestamp=1591858152806&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Ftypescript%2Fdownload%2Ftypescript-3.7.5.tgz", "integrity": "sha1-BpLiH2X9QQi5MwI4qsEd0uF3oa4=", "dev": true } @@ -2182,12 +2182,6 @@ "integrity": "sha1-HBJhu+qhCoBVu8XYq4S3sq/IRqA=", "dev": true }, - "@types/eslint-visitor-keys": { - "version": "1.0.0", - "resolved": "https://registry.npm.taobao.org/@types/eslint-visitor-keys/download/@types/eslint-visitor-keys-1.0.0.tgz", - "integrity": "sha1-HuMNeVRMqE1o1LPNsK9PIFZj3S0=", - "dev": true - }, "@types/estree": { "version": "0.0.39", "resolved": "https://registry.npm.taobao.org/@types/estree/download/@types/estree-0.0.39.tgz", @@ -2243,6 +2237,12 @@ "integrity": "sha1-OP1z3f2bVaux4bLtV4y1W9e30zk=", "dev": true }, + "@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4=", + "dev": true + }, "@types/minimatch": { "version": "3.0.3", "resolved": "https://registry.npm.taobao.org/@types/minimatch/download/@types/minimatch-3.0.3.tgz", @@ -2288,91 +2288,124 @@ "dev": true }, "@typescript-eslint/eslint-plugin": { - "version": "2.25.0", - "resolved": "https://registry.npm.taobao.org/@typescript-eslint/eslint-plugin/download/@typescript-eslint/eslint-plugin-2.25.0.tgz?cache=0&sync_timestamp=1585192870206&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40typescript-eslint%2Feslint-plugin%2Fdownload%2F%40typescript-eslint%2Feslint-plugin-2.25.0.tgz", - "integrity": "sha1-C2CRczLyDc/1TQ65viqen0yfvQI=", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.6.1.tgz", + "integrity": "sha512-SNZyflefTMK2JyrPfFFzzoy2asLmZvZJ6+/L5cIqg4HfKGiW2Gr1Go1OyEVqne/U4QwmoasuMwppoBHWBWF2nA==", "dev": true, "requires": { - "@typescript-eslint/experimental-utils": "2.25.0", + "@typescript-eslint/experimental-utils": "4.6.1", + "@typescript-eslint/scope-manager": "4.6.1", + "debug": "^4.1.1", "functional-red-black-tree": "^1.0.1", "regexpp": "^3.0.0", + "semver": "^7.3.2", "tsutils": "^3.17.1" }, "dependencies": { - "regexpp": { - "version": "3.0.0", - "resolved": "https://registry.npm.taobao.org/regexpp/download/regexpp-3.0.0.tgz", - "integrity": "sha1-3WOYLuMwDme0HBlW+FCqaA2dMw4=", + "@typescript-eslint/experimental-utils": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.6.1.tgz", + "integrity": "sha512-qyPqCFWlHZXkEBoV56UxHSoXW2qnTr4JrWVXOh3soBP3q0o7p4pUEMfInDwIa0dB/ypdtm7gLOS0hg0a73ijfg==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.3", + "@typescript-eslint/scope-manager": "4.6.1", + "@typescript-eslint/types": "4.6.1", + "@typescript-eslint/typescript-estree": "4.6.1", + "eslint-scope": "^5.0.0", + "eslint-utils": "^2.0.0" + } + }, + "@typescript-eslint/typescript-estree": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.6.1.tgz", + "integrity": "sha512-/J/kxiyjQQKqEr5kuKLNQ1Finpfb8gf/NpbwqFFYEBjxOsZ621r9AqwS9UDRA1Rrr/eneX/YsbPAIhU2rFLjXQ==", + "dev": true, + "requires": { + "@typescript-eslint/types": "4.6.1", + "@typescript-eslint/visitor-keys": "4.6.1", + "debug": "^4.1.1", + "globby": "^11.0.1", + "is-glob": "^4.0.1", + "lodash": "^4.17.15", + "semver": "^7.3.2", + "tsutils": "^3.17.1" + } + }, + "semver": { + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", "dev": true } } }, - "@typescript-eslint/experimental-utils": { - "version": "2.25.0", - "resolved": "https://registry.npm.taobao.org/@typescript-eslint/experimental-utils/download/@typescript-eslint/experimental-utils-2.25.0.tgz?cache=0&sync_timestamp=1585192867937&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40typescript-eslint%2Fexperimental-utils%2Fdownload%2F%40typescript-eslint%2Fexperimental-utils-2.25.0.tgz", - "integrity": "sha1-E2kcT+NovTd7HlseStZgsiC/dxQ=", + "@typescript-eslint/parser": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-4.6.1.tgz", + "integrity": "sha512-lScKRPt1wM9UwyKkGKyQDqf0bh6jm8DQ5iN37urRIXDm16GEv+HGEmum2Fc423xlk5NUOkOpfTnKZc/tqKZkDQ==", "dev": true, "requires": { - "@types/json-schema": "^7.0.3", - "@typescript-eslint/typescript-estree": "2.25.0", - "eslint-scope": "^5.0.0", - "eslint-utils": "^2.0.0" + "@typescript-eslint/scope-manager": "4.6.1", + "@typescript-eslint/types": "4.6.1", + "@typescript-eslint/typescript-estree": "4.6.1", + "debug": "^4.1.1" } }, - "@typescript-eslint/parser": { - "version": "2.25.0", - "resolved": "https://registry.npm.taobao.org/@typescript-eslint/parser/download/@typescript-eslint/parser-2.25.0.tgz?cache=0&sync_timestamp=1585192919196&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40typescript-eslint%2Fparser%2Fdownload%2F%40typescript-eslint%2Fparser-2.25.0.tgz", - "integrity": "sha1-q/s9mZCEgk2adW2bnA82+6A623Y=", + "@typescript-eslint/scope-manager": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.6.1.tgz", + "integrity": "sha512-f95+80r6VdINYscJY1KDUEDcxZ3prAWHulL4qRDfNVD0I5QAVSGqFkwHERDoLYJJWmEAkUMdQVvx7/c2Hp+Bjg==", "dev": true, "requires": { - "@types/eslint-visitor-keys": "^1.0.0", - "@typescript-eslint/experimental-utils": "2.25.0", - "@typescript-eslint/typescript-estree": "2.25.0", - "eslint-visitor-keys": "^1.1.0" + "@typescript-eslint/types": "4.6.1", + "@typescript-eslint/visitor-keys": "4.6.1" } }, + "@typescript-eslint/types": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.6.1.tgz", + "integrity": "sha512-k2ZCHhJ96YZyPIsykickez+OMHkz06xppVLfJ+DY90i532/Cx2Z+HiRMH8YZQo7a4zVd/TwNBuRCdXlGK4yo8w==", + "dev": true + }, "@typescript-eslint/typescript-estree": { - "version": "2.25.0", - "resolved": "https://registry.npm.taobao.org/@typescript-eslint/typescript-estree/download/@typescript-eslint/typescript-estree-2.25.0.tgz?cache=0&sync_timestamp=1585192865676&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40typescript-eslint%2Ftypescript-estree%2Fdownload%2F%40typescript-eslint%2Ftypescript-estree-2.25.0.tgz", - "integrity": "sha1-t5BJdVZzS3R2+n3T+lOZVaXHniw=", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.6.1.tgz", + "integrity": "sha512-/J/kxiyjQQKqEr5kuKLNQ1Finpfb8gf/NpbwqFFYEBjxOsZ621r9AqwS9UDRA1Rrr/eneX/YsbPAIhU2rFLjXQ==", "dev": true, "requires": { + "@typescript-eslint/types": "4.6.1", + "@typescript-eslint/visitor-keys": "4.6.1", "debug": "^4.1.1", - "eslint-visitor-keys": "^1.1.0", - "glob": "^7.1.6", + "globby": "^11.0.1", "is-glob": "^4.0.1", "lodash": "^4.17.15", - "semver": "^6.3.0", + "semver": "^7.3.2", "tsutils": "^3.17.1" }, "dependencies": { - "glob": { - "version": "7.1.6", - "resolved": "https://registry.npm.taobao.org/glob/download/glob-7.1.6.tgz", - "integrity": "sha1-FB8zuBp8JJLhJVlDB0gMRmeSeKY=", - "dev": true, - "requires": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - } - }, - "is-glob": { - "version": "4.0.1", - "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-4.0.1.tgz", - "integrity": "sha1-dWfb6fL14kZ7x3q4PEopSCQHpdw=", - "dev": true, - "requires": { - "is-extglob": "^2.1.1" - } - }, "semver": { - "version": "6.3.0", - "resolved": "https://registry.npm.taobao.org/semver/download/semver-6.3.0.tgz?cache=0&sync_timestamp=1581458063470&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsemver%2Fdownload%2Fsemver-6.3.0.tgz", - "integrity": "sha1-7gpkyK9ejO6mdoexM3YeG+y9HT0=", + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true + } + } + }, + "@typescript-eslint/visitor-keys": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.6.1.tgz", + "integrity": "sha512-owABze4toX7QXwOLT3/D5a8NecZEjEWU1srqxENTfqsY3bwVnl3YYbOh6s1rp2wQKO9RTHFGjKes08FgE7SVMw==", + "dev": true, + "requires": { + "@typescript-eslint/types": "4.6.1", + "eslint-visitor-keys": "^2.0.0" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz", + "integrity": "sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ==", "dev": true } } @@ -2383,6 +2416,12 @@ "integrity": "sha1-P6F3lwMrcUEOw3LhFmj0tP/IaoI=", "dev": true }, + "acorn": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", + "integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==", + "dev": true + }, "acorn-globals": { "version": "4.3.4", "resolved": "https://registry.npm.taobao.org/acorn-globals/download/acorn-globals-4.3.4.tgz", @@ -2408,9 +2447,9 @@ } }, "acorn-jsx": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.2.0.tgz", - "integrity": "sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.1.tgz", + "integrity": "sha512-K0Ptm/47OKfQRpNQ2J/oIN/3QYiK6FwW+eJbILhsdxh2WTLdl+30o8aGdTbm5JbffpFFAg/g+zi1E+jvJha5ng==", "dev": true }, "ajv": { @@ -2552,6 +2591,82 @@ "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", "dev": true }, + "array-includes": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.1.tgz", + "integrity": "sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0", + "is-string": "^1.0.5" + }, + "dependencies": { + "es-abstract": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.7.tgz", + "integrity": "sha512-VBl/gnfcJ7OercKA9MVaegWsBHFjV492syMudcnQZvt/Dw8ezpcOHYZXa/J96O8vx+g4x65YKhxOwDUh63aS5g==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "is-callable": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true + }, + "is-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, + "requires": { + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + } + } + }, "array-initial": { "version": "1.1.0", "resolved": "https://registry.npm.taobao.org/array-initial/download/array-initial-1.1.0.tgz", @@ -2624,6 +2739,81 @@ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", "dev": true }, + "array.prototype.flat": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz", + "integrity": "sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0-next.1" + }, + "dependencies": { + "es-abstract": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.7.tgz", + "integrity": "sha512-VBl/gnfcJ7OercKA9MVaegWsBHFjV492syMudcnQZvt/Dw8ezpcOHYZXa/J96O8vx+g4x65YKhxOwDUh63aS5g==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "is-callable": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true + }, + "is-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, + "requires": { + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + } + } + }, "asn1": { "version": "0.2.4", "resolved": "https://registry.npm.taobao.org/asn1/download/asn1-0.2.4.tgz", @@ -3063,6 +3253,16 @@ "unset-value": "^1.0.0" } }, + "call-bind": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.0.tgz", + "integrity": "sha512-AEXsYIyyDY3MCzbwdhzG3Jx1R0J2wetQyUynn6dYHAO+bg8l1k7jwZtRv4ryryFs7EP+NDlikJlVe59jr0cM2w==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.0" + } + }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npm.taobao.org/callsites/download/callsites-3.1.0.tgz", @@ -3210,9 +3410,9 @@ } }, "cli-width": { - "version": "2.2.0", - "resolved": "https://registry.npm.taobao.org/cli-width/download/cli-width-2.2.0.tgz", - "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", "dev": true }, "cliui": { @@ -3332,7 +3532,7 @@ }, "commondir": { "version": "1.0.1", - "resolved": "https://registry.npm.taobao.org/commondir/download/commondir-1.0.1.tgz", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", "dev": true }, @@ -3360,6 +3560,18 @@ "typedarray": "^0.0.6" } }, + "confusing-browser-globals": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/confusing-browser-globals/-/confusing-browser-globals-1.0.10.tgz", + "integrity": "sha512-gNld/3lySHwuhaVluJUKLePYirM3QNCKzVxqAdhJII9/WXKVX5PURzMVJspS1jTslSqjeuG4KMVTSouit5YPHA==", + "dev": true + }, + "contains-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", + "integrity": "sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=", + "dev": true + }, "convert-source-map": { "version": "1.7.0", "resolved": "https://registry.npm.taobao.org/convert-source-map/download/convert-source-map-1.7.0.tgz?cache=0&sync_timestamp=1573003637425&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fconvert-source-map%2Fdownload%2Fconvert-source-map-1.7.0.tgz", @@ -3833,22 +4045,22 @@ } }, "eslint": { - "version": "6.8.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-6.8.0.tgz", - "integrity": "sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-7.2.0.tgz", + "integrity": "sha512-B3BtEyaDKC5MlfDa2Ha8/D6DsS4fju95zs0hjS3HdGazw+LNayai38A25qMppK37wWGWNYSPOR6oYzlz5MHsRQ==", "dev": true, "requires": { "@babel/code-frame": "^7.0.0", "ajv": "^6.10.0", - "chalk": "^2.1.0", - "cross-spawn": "^6.0.5", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", "debug": "^4.0.1", "doctrine": "^3.0.0", - "eslint-scope": "^5.0.0", - "eslint-utils": "^1.4.3", - "eslint-visitor-keys": "^1.1.0", - "espree": "^6.1.2", - "esquery": "^1.0.1", + "eslint-scope": "^5.1.0", + "eslint-utils": "^2.0.0", + "eslint-visitor-keys": "^1.2.0", + "espree": "^7.1.0", + "esquery": "^1.2.0", "esutils": "^2.0.2", "file-entry-cache": "^5.0.1", "functional-red-black-tree": "^1.0.1", @@ -3861,45 +4073,103 @@ "is-glob": "^4.0.0", "js-yaml": "^3.13.1", "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.3.0", + "levn": "^0.4.1", "lodash": "^4.17.14", "minimatch": "^3.0.4", - "mkdirp": "^0.5.1", "natural-compare": "^1.4.0", - "optionator": "^0.8.3", + "optionator": "^0.9.1", "progress": "^2.0.0", - "regexpp": "^2.0.1", - "semver": "^6.1.2", - "strip-ansi": "^5.2.0", - "strip-json-comments": "^3.0.1", + "regexpp": "^3.1.0", + "semver": "^7.2.1", + "strip-ansi": "^6.0.0", + "strip-json-comments": "^3.1.0", "table": "^5.2.3", "text-table": "^0.2.0", "v8-compile-cache": "^2.0.3" }, "dependencies": { "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", "dev": true }, - "eslint-scope": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz", - "integrity": "sha512-oYrhJW7S0bxAFDvWqzvMPRm6pcgcnWc4QnofCAqRTRfQC0JcwenzGglTtsLyIuuWFfkqDG9vz67cnttSd53djw==", + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "esrecurse": "^4.1.0", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "requires": { + "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, - "eslint-utils": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.3.tgz", - "integrity": "sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==", + "eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", + "dev": true + }, + "esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", "dev": true, "requires": { - "eslint-visitor-keys": "^1.1.0" + "estraverse": "^5.2.0" + }, + "dependencies": { + "estraverse": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", + "dev": true + } } }, "globals": { @@ -3911,43 +4181,396 @@ "type-fest": "^0.8.1" } }, - "is-glob": { - "version": "4.0.1", - "resolved": "https://registry.npm.taobao.org/is-glob/download/is-glob-4.0.1.tgz", - "integrity": "sha1-dWfb6fL14kZ7x3q4PEopSCQHpdw=", + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", "dev": true, "requires": { - "is-extglob": "^2.1.1" + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" } }, "optionator": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", - "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", + "integrity": "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==", "dev": true, "requires": { - "deep-is": "~0.1.3", - "fast-levenshtein": "~2.0.6", - "levn": "~0.3.0", - "prelude-ls": "~1.1.2", - "type-check": "~0.3.2", - "word-wrap": "~1.2.3" + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.3" } }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true + }, "semver": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", - "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.2.tgz", + "integrity": "sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", "dev": true }, "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", "dev": true, "requires": { - "ansi-regex": "^4.1.0" + "ansi-regex": "^5.0.0" } + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "requires": { + "prelude-ls": "^1.2.1" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "eslint-config-airbnb-base": { + "version": "14.2.1", + "resolved": "https://registry.npmjs.org/eslint-config-airbnb-base/-/eslint-config-airbnb-base-14.2.1.tgz", + "integrity": "sha512-GOrQyDtVEc1Xy20U7vsB2yAoB4nBlfH5HZJeatRXHleO+OS5Ot+MWij4Dpltw4/DyIkqUfqz1epfhVR5XWWQPA==", + "dev": true, + "requires": { + "confusing-browser-globals": "^1.0.10", + "object.assign": "^4.1.2", + "object.entries": "^1.1.2" + }, + "dependencies": { + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + } + } + }, + "eslint-import-resolver-node": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz", + "integrity": "sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA==", + "dev": true, + "requires": { + "debug": "^2.6.9", + "resolve": "^1.13.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "eslint-module-utils": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz", + "integrity": "sha512-6j9xxegbqe8/kZY8cYpcp0xhbK0EgJlg3g9mib3/miLaExuuwc3n5UEfSnU6hWMbT0FAYVvDbL9RrRgpUeQIvA==", + "dev": true, + "requires": { + "debug": "^2.6.9", + "pkg-dir": "^2.0.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "pkg-dir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", + "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", + "dev": true, + "requires": { + "find-up": "^2.1.0" + } + } + } + }, + "eslint-plugin-import": { + "version": "2.22.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.22.1.tgz", + "integrity": "sha512-8K7JjINHOpH64ozkAhpT3sd+FswIZTfMZTjdx052pnWrgRCVfp8op9tbjpAk3DdUeI/Ba4C8OjdC0r90erHEOw==", + "dev": true, + "requires": { + "array-includes": "^3.1.1", + "array.prototype.flat": "^1.2.3", + "contains-path": "^0.1.0", + "debug": "^2.6.9", + "doctrine": "1.5.0", + "eslint-import-resolver-node": "^0.3.4", + "eslint-module-utils": "^2.6.0", + "has": "^1.0.3", + "minimatch": "^3.0.4", + "object.values": "^1.1.1", + "read-pkg-up": "^2.0.0", + "resolve": "^1.17.0", + "tsconfig-paths": "^3.9.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "doctrine": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz", + "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=", + "dev": true, + "requires": { + "esutils": "^2.0.2", + "isarray": "^1.0.0" + } + }, + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "load-json-file": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", + "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "strip-bom": "^3.0.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "path-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", + "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", + "dev": true, + "requires": { + "pify": "^2.0.0" + } + }, + "read-pkg": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", + "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", + "dev": true, + "requires": { + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" + } + }, + "read-pkg-up": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", + "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", + "dev": true, + "requires": { + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" + } + }, + "resolve": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.18.1.tgz", + "integrity": "sha512-lDfCPaMKfOJXjy0dPayzPdF1phampNWr3qFCjAu+rw/qbQmr5jWH5xN2hwh9QKfw9E5v4hwV7A+jrCmL8yjjqA==", + "dev": true, + "requires": { + "is-core-module": "^2.0.0", + "path-parse": "^1.0.6" + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true } } }, @@ -3977,20 +4600,20 @@ "dev": true }, "espree": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-6.2.1.tgz", - "integrity": "sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw==", + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-7.3.0.tgz", + "integrity": "sha512-dksIWsvKCixn1yrEXO8UosNSxaDoSYpq9reEjZSbHLpT5hpaCAKTLBwq0RHtLrIr+c0ByiYzWT8KTMRzoRCNlw==", "dev": true, "requires": { - "acorn": "^7.1.1", + "acorn": "^7.4.0", "acorn-jsx": "^5.2.0", - "eslint-visitor-keys": "^1.1.0" + "eslint-visitor-keys": "^1.3.0" }, "dependencies": { - "acorn": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.1.1.tgz", - "integrity": "sha512-add7dgA5ppRPxCFJoAGfMDi7PIBXq1RtGo7BhbLaxwrXPOmw8gq48Y9ozT01hUKy9byMjlR20EJhu5zlkErEkg==", + "eslint-visitor-keys": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz", + "integrity": "sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ==", "dev": true } } @@ -4002,12 +4625,20 @@ "dev": true }, "esquery": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.1.0.tgz", - "integrity": "sha512-MxYW9xKmROWF672KqjO75sszsA8Mxhw06YFeS5VHlB98KDHbOSurm3ArsjO60Eaf3QmGMCP1yn+0JQkNLo/97Q==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.3.1.tgz", + "integrity": "sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ==", "dev": true, "requires": { - "estraverse": "^4.0.0" + "estraverse": "^5.1.0" + }, + "dependencies": { + "estraverse": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.2.0.tgz", + "integrity": "sha512-BxbNGGNm0RyRYvUdHpIwv9IWzeM9XClbOxwoATuFdOE7ZE6wHL+HQ5T8hoPM+zHvmKzzsEqhgy0GrQ5X13afiQ==", + "dev": true + } } }, "esrecurse": { @@ -4492,9 +5123,9 @@ } }, "flatted": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.1.tgz", - "integrity": "sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz", + "integrity": "sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==", "dev": true }, "flush-write-stream": { @@ -5233,6 +5864,17 @@ "integrity": "sha1-+Xj6TJDR3+f/LWvtoqUV5xO9z0o=", "dev": true }, + "get-intrinsic": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.0.1.tgz", + "integrity": "sha512-ZnWP+AmS1VUaLgTRy47+zKtjTxz+0xMpx3I52i+aalBK1QP19ggLF3Db89KJX7kjfOfP2eoa01qc++GwPgufPg==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + } + }, "get-stream": { "version": "4.1.0", "resolved": "https://registry.npm.taobao.org/get-stream/download/get-stream-4.1.0.tgz", @@ -5701,9 +6343,9 @@ "dev": true }, "import-fresh": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.2.1.tgz", - "integrity": "sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==", + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.2.2.tgz", + "integrity": "sha512-cTPNrlvJT6twpYy+YmKUKrTSjWFs3bjYjAhCwm+z4EOCubZxAuO+hHpRN64TqjEaYSHs7tJAE0w1CKMGmsG/lw==", "dev": true, "requires": { "parent-module": "^1.0.0", @@ -5749,21 +6391,21 @@ "dev": true }, "inquirer": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.1.0.tgz", - "integrity": "sha512-5fJMWEmikSYu0nv/flMc475MhGbB7TSPd/2IpFV4I4rMklboCH2rQjYY5kKiYGHqUF9gvaambupcJFFG9dvReg==", + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.3.3.tgz", + "integrity": "sha512-JG3eIAj5V9CwcGvuOmoo6LB9kbAYT8HXffUl6memuszlwDC/qvFAJw49XJ5NROSFNPxp3iQg1GqkFhaY/CR0IA==", "dev": true, "requires": { "ansi-escapes": "^4.2.1", - "chalk": "^3.0.0", + "chalk": "^4.1.0", "cli-cursor": "^3.1.0", - "cli-width": "^2.0.0", + "cli-width": "^3.0.0", "external-editor": "^3.0.3", "figures": "^3.0.0", - "lodash": "^4.17.15", + "lodash": "^4.17.19", "mute-stream": "0.0.8", "run-async": "^2.4.0", - "rxjs": "^6.5.3", + "rxjs": "^6.6.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0", "through": "^2.3.6" @@ -5785,19 +6427,18 @@ "dev": true }, "ansi-styles": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", - "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "requires": { - "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, "chalk": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", - "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", "dev": true, "requires": { "ansi-styles": "^4.1.0", @@ -5837,6 +6478,12 @@ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true }, + "lodash": { + "version": "4.17.20", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", + "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==", + "dev": true + }, "string-width": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", @@ -5858,9 +6505,9 @@ } }, "supports-color": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", - "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "requires": { "has-flag": "^4.0.0" @@ -6039,6 +6686,15 @@ "integrity": "sha1-fRQK3DiarzARqPKipM+m+q3/sRg=", "dev": true }, + "is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, "is-module": { "version": "1.0.0", "resolved": "https://registry.npm.taobao.org/is-module/download/is-module-1.0.0.tgz", @@ -6051,6 +6707,12 @@ "integrity": "sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI=", "dev": true }, + "is-negative-zero": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.0.tgz", + "integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE=", + "dev": true + }, "is-number": { "version": "3.0.0", "resolved": "https://registry.npm.taobao.org/is-number/download/is-number-3.0.0.tgz", @@ -6080,12 +6742,6 @@ "isobject": "^3.0.1" } }, - "is-promise": { - "version": "2.1.0", - "resolved": "https://registry.npm.taobao.org/is-promise/download/is-promise-2.1.0.tgz", - "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", - "dev": true - }, "is-reference": { "version": "1.2.1", "resolved": "https://registry.npm.taobao.org/is-reference/download/is-reference-1.2.1.tgz", @@ -6119,6 +6775,12 @@ "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", "dev": true }, + "is-string": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz", + "integrity": "sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ==", + "dev": true + }, "is-symbol": { "version": "1.0.2", "resolved": "https://registry.npm.taobao.org/is-symbol/download/is-symbol-1.0.2.tgz", @@ -7239,9 +7901,9 @@ "dev": true }, "js-yaml": { - "version": "3.13.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", - "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.0.tgz", + "integrity": "sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A==", "dev": true, "requires": { "argparse": "^1.0.7", @@ -7999,6 +8661,82 @@ "isobject": "^3.0.0" } }, + "object.entries": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.2.tgz", + "integrity": "sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5", + "has": "^1.0.3" + }, + "dependencies": { + "es-abstract": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.7.tgz", + "integrity": "sha512-VBl/gnfcJ7OercKA9MVaegWsBHFjV492syMudcnQZvt/Dw8ezpcOHYZXa/J96O8vx+g4x65YKhxOwDUh63aS5g==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "is-callable": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true + }, + "is-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, + "requires": { + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + } + } + }, "object.getownpropertydescriptors": { "version": "2.0.3", "resolved": "https://registry.npm.taobao.org/object.getownpropertydescriptors/download/object.getownpropertydescriptors-2.0.3.tgz", @@ -8038,6 +8776,83 @@ "make-iterator": "^1.0.0" } }, + "object.values": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.1.tgz", + "integrity": "sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.0-next.1", + "function-bind": "^1.1.1", + "has": "^1.0.3" + }, + "dependencies": { + "es-abstract": { + "version": "1.17.7", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.7.tgz", + "integrity": "sha512-VBl/gnfcJ7OercKA9MVaegWsBHFjV492syMudcnQZvt/Dw8ezpcOHYZXa/J96O8vx+g4x65YKhxOwDUh63aS5g==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "is-callable": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true + }, + "is-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, + "requires": { + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + } + } + }, "once": { "version": "1.4.0", "resolved": "https://registry.npm.taobao.org/once/download/once-1.4.0.tgz", @@ -8047,6 +8862,15 @@ "wrappy": "1" } }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + }, "opener": { "version": "1.4.3", "resolved": "https://registry.npm.taobao.org/opener/download/opener-1.4.3.tgz", @@ -8111,7 +8935,7 @@ }, "os-tmpdir": { "version": "1.0.2", - "resolved": "https://registry.npm.taobao.org/os-tmpdir/download/os-tmpdir-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", "dev": true }, @@ -8744,9 +9568,9 @@ } }, "regexpp": { - "version": "2.0.1", - "resolved": "https://registry.npm.taobao.org/regexpp/download/regexpp-2.0.1.tgz?cache=0&sync_timestamp=1567160849322&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fregexpp%2Fdownload%2Fregexpp-2.0.1.tgz", - "integrity": "sha1-jRnTHPYySCtYkEn4KB+T28uk0H8=", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.1.0.tgz", + "integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==", "dev": true }, "regexpu-core": { @@ -8991,17 +9815,6 @@ "requires": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" - }, - "dependencies": { - "onetime": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", - "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", - "dev": true, - "requires": { - "mimic-fn": "^2.1.0" - } - } } }, "ret": { @@ -9089,13 +9902,10 @@ "dev": true }, "run-async": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.0.tgz", - "integrity": "sha512-xJTbh/d7Lm7SBhc1tNvTpeCHaEzoyxPrqNlvSdMfBTYwaY++UJFyXUOxAtsRUXjlqOfj8luNaR9vjCh4KeV+pg==", - "dev": true, - "requires": { - "is-promise": "^2.1.0" - } + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true }, "run-parallel": { "version": "1.1.10", @@ -9104,9 +9914,9 @@ "dev": true }, "rxjs": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.4.tgz", - "integrity": "sha512-naMQXcgEo3csAEGvw/NydRA0fuS2nDZJiw1YUWFKU7aPPAPGZEsD4Iimit96qwCieH6y614MCLYwdkrWx7z/7Q==", + "version": "6.6.3", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.3.tgz", + "integrity": "sha512-trsQc+xYYXZ3urjOiJOuCOa5N3jAZ3eiSpQB5hIT8zGlL2QfnHLJ2r7GMkBGuIausdJN1OneaI6gQlsqNHHmZQ==", "dev": true, "requires": { "tslib": "^1.9.0" @@ -9226,7 +10036,7 @@ }, "shelljs": { "version": "0.8.4", - "resolved": "https://registry.npm.taobao.org/shelljs/download/shelljs-0.8.4.tgz?cache=0&sync_timestamp=1587787210621&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fshelljs%2Fdownload%2Fshelljs-0.8.4.tgz", + "resolved": "https://registry.npm.taobao.org/shelljs/download/shelljs-0.8.4.tgz", "integrity": "sha1-3naE/ut2f4cWsyYHiooAh1iQ48I=", "dev": true, "requires": { @@ -9496,7 +10306,7 @@ }, "sprintf-js": { "version": "1.0.3", - "resolved": "https://registry.npm.taobao.org/sprintf-js/download/sprintf-js-1.0.3.tgz", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, @@ -9623,6 +10433,82 @@ } } }, + "string.prototype.trimend": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.2.tgz", + "integrity": "sha512-8oAG/hi14Z4nOVP0z6mdiVZ/wqjDtWSLygMigTzAb+7aPEDTleeFf+WrF+alzecxIRkckkJVn+dTlwzJXORATw==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.18.0-next.1" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0-next.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", + "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-negative-zero": "^2.0.0", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "is-callable": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true + }, + "is-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, + "requires": { + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + } + } + }, "string.prototype.trimleft": { "version": "2.1.0", "resolved": "https://registry.npm.taobao.org/string.prototype.trimleft/download/string.prototype.trimleft-2.1.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstring.prototype.trimleft%2Fdownload%2Fstring.prototype.trimleft-2.1.0.tgz", @@ -9643,6 +10529,82 @@ "function-bind": "^1.1.1" } }, + "string.prototype.trimstart": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.2.tgz", + "integrity": "sha512-7F6CdBTl5zyu30BJFdzSTlSlLPwODC23Od+iLoVH8X6+3fvDPPuBVVj9iaB1GOsSTSIgVfsfm27R2FGrAPznWg==", + "dev": true, + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.18.0-next.1" + }, + "dependencies": { + "es-abstract": { + "version": "1.18.0-next.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", + "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.1", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1", + "is-callable": "^1.2.2", + "is-negative-zero": "^2.0.0", + "is-regex": "^1.1.1", + "object-inspect": "^1.8.0", + "object-keys": "^1.1.1", + "object.assign": "^4.1.1", + "string.prototype.trimend": "^1.0.1", + "string.prototype.trimstart": "^1.0.1" + } + }, + "es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "is-callable": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true + }, + "is-regex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", + "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, + "requires": { + "has-symbols": "^1.0.1" + } + }, + "object-inspect": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true + }, + "object.assign": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", + "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.0", + "define-properties": "^1.1.3", + "has-symbols": "^1.0.1", + "object-keys": "^1.1.1" + } + } + } + }, "strip-ansi": { "version": "3.0.1", "resolved": "http://registry.npm.taobao.org/strip-ansi/download/strip-ansi-3.0.1.tgz", @@ -9668,9 +10630,9 @@ "dev": true }, "strip-json-comments": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.0.1.tgz", - "integrity": "sha512-VTyMAUfdm047mwKl+u79WIdrZxtFtn+nBxHeb844XBQ9uMNTuTHdx2hc5RiAJYqwTj3wc/xe5HLSdJSkJ+WfZw==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true }, "supports-color": { @@ -9877,7 +10839,7 @@ }, "text-table": { "version": "0.2.0", - "resolved": "https://registry.npm.taobao.org/text-table/download/text-table-0.2.0.tgz", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", "dev": true }, @@ -10036,7 +10998,7 @@ }, "through": { "version": "2.3.8", - "resolved": "https://registry.npm.taobao.org/through/download/through-2.3.8.tgz", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", "dev": true }, @@ -10442,6 +11404,35 @@ } } }, + "tsconfig-paths": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz", + "integrity": "sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw==", + "dev": true, + "requires": { + "@types/json5": "^0.0.29", + "json5": "^1.0.1", + "minimist": "^1.2.0", + "strip-bom": "^3.0.0" + }, + "dependencies": { + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true + } + } + }, "tslib": { "version": "1.10.0", "resolved": "https://registry.npm.taobao.org/tslib/download/tslib-1.10.0.tgz", @@ -10519,7 +11510,7 @@ "dependencies": { "fs-extra": { "version": "8.1.0", - "resolved": "https://registry.npm.taobao.org/fs-extra/download/fs-extra-8.1.0.tgz?cache=0&sync_timestamp=1591229972229&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Ffs-extra%2Fdownload%2Ffs-extra-8.1.0.tgz", + "resolved": "https://registry.npm.taobao.org/fs-extra/download/fs-extra-8.1.0.tgz", "integrity": "sha1-SdQ8RaiM2Wd2aMt74bRu/bjS4cA=", "dev": true, "requires": { @@ -10561,7 +11552,7 @@ }, "source-map": { "version": "0.6.1", - "resolved": "https://registry.npm.taobao.org/source-map/download/source-map-0.6.1.tgz?cache=0&sync_timestamp=1571657176668&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsource-map%2Fdownload%2Fsource-map-0.6.1.tgz", + "resolved": "https://registry.npm.taobao.org/source-map/download/source-map-0.6.1.tgz", "integrity": "sha1-dHIq8y6WFOnCh6jQu95IteLxomM=", "dev": true }, @@ -10600,7 +11591,7 @@ "dependencies": { "semver": { "version": "7.3.2", - "resolved": "https://registry.npm.taobao.org/semver/download/semver-7.3.2.tgz", + "resolved": "https://registry.npm.taobao.org/semver/download/semver-7.3.2.tgz?cache=0&sync_timestamp=1586886267748&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsemver%2Fdownload%2Fsemver-7.3.2.tgz", "integrity": "sha1-YElisFK4HtB4aq6EOJ/7pw/9OTg=", "dev": true } @@ -10640,7 +11631,7 @@ }, "underscore": { "version": "1.10.2", - "resolved": "https://registry.npm.taobao.org/underscore/download/underscore-1.10.2.tgz?cache=0&sync_timestamp=1585603748606&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Funderscore%2Fdownload%2Funderscore-1.10.2.tgz", + "resolved": "https://registry.npm.taobao.org/underscore/download/underscore-1.10.2.tgz", "integrity": "sha1-c9aqNmjzGI5K2w8ZQ70Sz9fvqq8=", "dev": true }, @@ -10842,9 +11833,9 @@ "dev": true }, "v8-compile-cache": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.1.0.tgz", - "integrity": "sha512-usZBT3PW+LOjM25wbqIlZwPeJV+3OSz3M1k1Ws8snlW39dZyYL9lOGC5FgPVHfk0jKmjiDV8Z0mIbVQPiwFs7g==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.2.0.tgz", + "integrity": "sha512-gTpR5XQNKFwOd4clxfnhaqvfqMpqEwr4tOtCyz4MtYZX2JYhfr1JvBFKdS+7K/9rfpZR3VLX+YWBbKoxCgS43Q==", "dev": true }, "v8flags": { diff --git a/package.json b/package.json index e9e5d7fd5c..4c8c74e958 100644 --- a/package.json +++ b/package.json @@ -32,11 +32,13 @@ "@types/fs-extra": "^5.0.4", "@types/jest": "^24.0.25", "@types/yargs": "^12.0.14", - "@typescript-eslint/eslint-plugin": "^2.24.0", - "@typescript-eslint/parser": "^2.24.0", + "@typescript-eslint/eslint-plugin": "^4.6.1", + "@typescript-eslint/parser": "^4.6.1", "commander": "^2.20.3", "dat.gui": "^0.7.5", - "eslint": "^6.8.0", + "eslint": "^7.2.0", + "eslint-config-airbnb-base": "^14.2.1", + "eslint-plugin-import": "^2.22.1", "fs-extra": "^7.0.1", "gulp": "^4.0.2", "http-server": "^0.11.1", diff --git a/tslint.json b/tslint.json deleted file mode 100644 index 2b4146413f..0000000000 --- a/tslint.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "defaultSeverity": "error", - "extends": [ - "tslint:recommended" - ], - "jsRules": {}, - "rules": { - "quotemark": [ - true, - "single" - ], - "one-line": [ - true, - "check-open-brace" - ], - "no-namespace": false, - "no-console": false, - "space-before-function-paren": true, - "max-classes-per-file": false, - "variable-name": false, - "object-literal-sort-keys": false, - "ban-types": false, - "no-bitwise": false, - "no-empty": false, - "radix": false, - "prefer-for-of": false, - "forin":false, - - "max-line-length": [ - true, - 160 - ] - }, - "rulesDirectory": [] -}